Knight Moves UVA - 439
这题比较简单,对于我这种学弱学习bfs再好不过了。
下面是代码:
/*************************************************************************
> File Name: Knight Moves UVA - 439
> Author: Mrhanice
> Mail: 690697134@qq.com
> Created Time: 20170315
> link : https://vjudge.net/problem/UVA-439
************************************************************************/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
struct step
{
int x,y,time;
step(int a,int b,int c):x(a),y(b),time(c){}
step(){}
};
int start_x,start_y,end_x,end_y;
int M[10][10];
int d[8][2]={{-2,1},{-2,-1},{-1,2},{-1,-2},{1,2},{1,-2},{2,1},{2,-1}};
int bfs(step temp)
{
if(temp.x==end_x&&temp.y==end_y) return 0;
memset(M,0,sizeof(M));//要记得每次都清空啊;
queue <step> q;
q.push(temp);
M[temp.x][temp.y]=1;
while(!q.empty())
{
for(int i=0;i<8;i++)
{
step t=q.front();
t.x+=d[i][0];
t.y+=d[i][1];
if(t.x>0&&t.x<9&&t.y>0&&t.y<9)
{
if(!M[t.x][t.y]&&t.x==end_x&&t.y==end_y)
{
return t.time+1;
}
step add(t.x,t.y,t.time+1);
if(!M[t.x][t.y])
{
q.push(add);
}
M[t.x][t.y]=1;
}
}
q.pop();
}
}
int main()
{
char st[10],ed[10];
while(scanf("%s %s",st,ed)!=EOF)
{
start_x=st[0]-'a'+1;
start_y=st[1]-'0';
end_x=ed[0]-'a'+1;
end_y=ed[1]-'0';
step temp(start_x,start_y,0);
printf("To get from %s to %s takes %d knight moves.\n",st,ed,bfs(temp));
}
return 0;
}