标签:
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 <iostream> #include<deque> #include<cstring> #include<cstdio> using namespace std; struct node { int x,y,num; }; deque<node> s; int dr[8][2]={{2,1},{2,-1},{1,2},{1,-2},{-2,-1},{-2,1},{-1,-2},{-1,2} }; int vis[10][10]; int ans,i,sx,sy,tx,ty; char ch1[4],ch2[4]; void bfs() { node p; p.x=sx; p.y=sy; p.num=0; s.clear(); vis[sx][sy]=1; s.push_back(p); while(!s.empty()) { node q=s.front(); for(int i=0;i<8;i++) { int xx=q.x+dr[i][0]; int yy=q.y+dr[i][1]; if(xx>0 && xx<=8 && yy>0 && yy<=8 && !vis[xx][yy]) { p.x=xx; p.y=yy; p.num=q.num+1; s.push_back(p); vis[xx][yy]=1; if (xx==tx && yy==ty) {ans=p.num; return;} } } s.pop_front(); } return; } int main() { while(~scanf("%s %s",&ch1,&ch2)) { ans=0; sx=ch1[0]-‘a‘+1; sy=ch1[1]-‘0‘; tx=ch2[0]-‘a‘+1; ty=ch2[1]-‘0‘; memset(vis,0,sizeof(vis)); if (sx!=tx || sy!=ty) bfs(); printf("To get from %s to %s takes %d knight moves.\n",ch1,ch2,ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/stepping/p/5667490.html