个人理解像这种在图里面寻找最短路线的问题,用bfs更靠谱。
宽度优先搜索,能够一层一层往下搜,更方便计数step。
dfs 则思路简单,代码难度小一些,在许多情况下更适合遍历。
方法就是比较普遍的方法,很好理解的。看过刘汝佳的书就能做出来。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
int a1,a2,b1,b2;
int ch1,ch2,ch;
int q[20000];
int dist[100][100];
const int dx[]={1,2,-1,-2,1,2,-1,-2};
const int dy[]={2,1,-2,-1,-2,-1,2,1};
int bfs(int x,int y)
{
if(x==a2&&y==b2)
{
dist[a2][b2]=0;
return 0;
}
int u;
int xx,yy;
int front=0;int rear=0;
u=8*x+y;
dist[x][y]=0;
q[rear++]=u;
while(front<rear)
{
u=q[front++];
x=u/8;y=u%8;
if(y%8==0)
{
y=8;
x=x-1;
}
for(int d=0;d<8;d++)
{
int newx=x+dx[d];
int newy=y+dy[d];
if(newx>=1&&newx<=8&&newy>=1&&newy<=8)
{
int v=newx*8+newy;
q[rear++]=v;
dist[newx][newy]=dist[x][y]+1;
if(newx==a2&&newy==b2)
return 0;
}
}
}
return 0;
}
int main()
{
char ch1,ch2,ch;
while(scanf("%c%d %c%d%c",&ch1,&a1,&ch2,&a2,&ch)!=EOF)
{
memset(dist,0,sizeof(dist));
b1=ch1-'a'+1;
b2=ch2-'a'+1;
bfs(a1,b1);
printf("To get from %c%d to %c%d takes %d knight moves.\n",ch1,a1,ch2,a2,dist[a2][b2]);
}
return 0;
}