//这是一道我曾经不会做的题,现在还是能做了,特此记录一下//
AC代码:
#include<stdio.h> #include<string.h> #define max 50 char a[max][max]; int vis[max][max]; int dir[8][2]={{2,1},{-2,1},{2,-1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}}; struct node { int x,y,step; }queue[max*max]; char s1[max]; char s2[max]; int x1,y1,x2,y2; void bfs(int x,int y) { struct node now,pre; queue[0].x=x1; queue[0].y=y1; queue[0].step=0; int e=0,h=1; while(e<h) { pre=queue[e]; if(pre.x==x2&&pre.y==y2) { printf("%d knight moves.\n",pre.step); return; } int i; for(i=0;i<8;i++) { now.x=pre.x+dir[i][0]; now.y=pre.y+dir[i][1]; now.step=pre.step+1; if(now.x>=1&&now.x<=8&&now.y>=1&&now.y<=8&&!vis[now.x][now.y]) { vis[now.x][now.y]=1; queue[h++]=now; } } e++; } } int main() { while(scanf("%s%s",s1,s2)!=EOF) { memset(vis,0,sizeof(vis)); x1=s1[0]-'a'+1; y1=s1[1]-'0'; x2=s2[0]-'a'+1; y2=s2[1]-'0'; printf("To get from %s to %s takes ",s1,s2); bfs(x1,y1); } return 0; }