e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
#include <stdio.h> #include <queue> #include <string.h> #include <algorithm> using namespace std; int vis[10][10]; int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; //马的八个方向 int sx,sy; struct node { int x,y; int step; } ; bool check(int x,int y) { if(x>8 ||x<1 ||y>8 ||y<1 ||vis[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; vis[ed.x][ed.y]=1; q.push(ed); } } } int main() { char s[22]; char s1[22]; int x2,y2; int i,j; while(scanf("%s%s",s,s1)!=EOF) { sx=s1[0]-'a'+1; sy=s1[1]-'0'; x2=s[0]-'a'+1; y2=s[1]-'0'; // 控制好输入 // printf("%d %d\n",x2,y2); // 用这个可以检查转为后的坐标 // printf("%d %d\n",sx,sy); memset(vis,0,sizeof(vis)); vis[x2][y2]=1; int ans=bfs(x2,y2); //裸BFS printf("To get from %s to %s takes %d knight moves.\n",s,s1,ans); } return 0; }
原文地址:http://blog.csdn.net/sky_miange/article/details/43604211