#include#include #include using namespace std;struct node{ int x; int y; int step;} cur,next,st,ed;int dir[8][2]= {-1,-2,-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2};char start[4],end[4];int map[10][10];queue q;int judge(int x,int y){ if(x<0||x>7||y<0||y>7)return 1; if(map[x][y])return 1; return 0;}int BFS(){ int i; int step=0; memset(map,0,sizeof(map)); while(!q.empty())q.pop(); st.x=start[0]-'a'; st.y=start[1]-'1'; st.step=0; ed.x=end[0]-'a'; ed.y=end[1]-'1'; q.push(st); while(!q.empty()) { cur=q.front(); q.pop(); if(cur.x==ed.x&&cur.y==ed.y)return step; for(i=0; i<8; i++) { next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; if(judge(next.x,next.y))continue; if(next.x==ed.x&&next.y==ed.y)return cur.step+1; next.step=cur.step+1; map[next.x][next.y]=1; q.push(next); } //step++; } return 0;}int main(){ while(scanf("%s %s",start,end)!=EOF) { //printf("%s %s\n",start,end); int ans=BFS(); printf("To get from %s to %s takes %d knight moves.\n",start,end,ans); memset(start,0,sizeof(start)); memset(end,0,sizeof(end)); } return 0;}
题意为马走日,典型的BFS搜索@#@