#include<cstdio> #include<cstring> #include<queue> using namespace std; typedef struct{ int px; int py; int dis; }node; queue<node>q; int main() { char cx,cy; int a,b,i,j,x,y,m,n; bool map[9][9]; node tmp,s[85]; while(scanf("%c%d %c%d",&cx,&a,&cy,&b)!=EOF) { memset(map,0,sizeof(map)); memset(s,0,sizeof(s)); x=cx-'a';y=cy-'a'; s[i=0].px=x; s[0].py=a; s[0].dis=0; q.push(s[0]); tmp=s[0]; map[x][a]=1; //printf("x=%d a=%d\n",s[i=0].px,s[0].py=a); //printf("y=%c b=%d\n",cy,b); //printf("tempwaipx=%d waipy=%d\n",q.front().px,q.front().py); while(!q.empty()) { tmp=q.front();//printf("px=%d py=%d\n",tmp.px,tmp.py); //printf("neipx=%d neipy=%d\n",q.front().px,q.front().py); if(tmp.px==y&&tmp.py==b){printf("To get from %c%d to %c%d takes %d knight moves.\n",cx,a,cy,b,tmp.dis);break;} q.pop(); m=tmp.px; n=tmp.py; if(m+2<=7&&n+1<=8&&!map[m+2][n+1]){i++;s[i].px=m+2;s[i].py=n+1;map[m+2][n+1]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m+1<=7&&n+2<=8&&!map[m+1][n+2]){i++;s[i].px=m+1;s[i].py=n+2;map[m+1][n+2]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m-2>=0&&n+1<=8&&!map[m-2][n+1]){i++;s[i].px=m-2;s[i].py=n+1;map[m-2][n+1]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m+2<=7&&n-1>=1&&!map[m+2][n-1]){i++;s[i].px=m+2;s[i].py=n-1;map[m+2][n-1]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m-2>=0&&n-1>=1&&!map[m-2][n-1]){i++;s[i].px=m-2;s[i].py=n-1;map[m-2][n-1]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m+1<=7&&n-2>=1&&!map[m+1][n-2]){i++;s[i].px=m+1;s[i].py=n-2;map[m+1][n-2]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m-1>=0&&n+2<=8&&!map[m-1][n+2]){i++;s[i].px=m-1;s[i].py=n+2;map[m-1][n+2]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} if(m-1>=0&&n-2>=1&&!map[m-1][n-2]){i++;s[i].px=m-1;s[i].py=n-2;map[m-1][n-2]=1;s[i].dis=tmp.dis+1;q.push(s[i]);} } while(!q.empty())q.pop(); getchar(); } return 0; }
总结
一、很失败的写代码经历,memset(map,0,sizeof(map));我写成memset(map,0,sizeof(0));调试了N久……
二、经验:
1、如果出现运行错误很可能是自己判断是否越界的地方出现问题
2、第一次运行对但第二次运行错误 有两种可能 一是第二次读入数据错误 二是没有清空第一次的