#include <stdio.h> #include<algorithm> #include<string.h> #include<stdlib.h> #include<queue> using namespace std; int vist[100][100]; int sx,sy; int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; struct node { int x,y; int step; }; bool check(int x,int y) { if(x>8||x<1||y>8||y<1||vist[x][y]) return 0; return 1; } int bfs(int x,int y) { node st,ed; int i; queue<node>q; st.x=x; st.y=y; st.step=0; q.push(st); while(!q.empty()) { st=q.front(); q.pop(); if(st.x==sx&&st.y==sy) return st.step; for(i=0;i<8;i++) { ed.x=st.x+dir[i][0]; ed.y=st.y+dir[i][1]; if(!check(ed.x,ed.y)) continue; ed.step=st.step+1; vist[ed.x][ed.y]=1; q.push(ed); } } return 0; } int main() { char a[20],a1[20]; int x2,y2; while(scanf("%s%s",a,a1)!=EOF) { sx=a1[0]-'a'+1; sy=a1[1]-'0'; x2=a[0]-'a'+1; y2=a[1]-'0'; memset(vist,0,sizeof(vist)); vist[x2][y2]=1; int ans=bfs(x2,y2); printf("To get from %s to %s takes %d knight moves.\n",a,a1,ans); } return 0; } |
Double click to view unformatted code.