A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
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<string.h> #include<algorithm> #include<math.h> #include<queue> #include<iostream> #define N 55 using namespace std; int a,b,c,d; char A,B,C,D; bool map[9][9]; int f[8][2]= {{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; struct node { int x,y,t; }; bool check(int x,int y) { if(x<0||y<0||x>=8||y>=8||map[x][y]) return 0; return 1; } void bfs() { queue<node> q; node first,next; first.x=a; first.y=b; first.t=0; q.push(first); map[first.x][first.y]=1; while(!q.empty()) { first=q.front(); q.pop(); for(int i=0; i<8; i++) { next.x=first.x+f[i][0]; next.y=first.y+f[i][1]; if(next.x==c&&next.y==d) { printf("To get from %c%c to %c%c takes %d knight moves.\n",A,B,C,D,first.t+1); return ; } if(check(next.x,next.y)) { next.t=first.t+1; q.push(next); map[next.x][next.y]=1; } } } return ; } int main() { while(~scanf("%c%c%*c%c%c",&A,&B,&C,&D)) { getchar(); memset(map,0,sizeof(map)); a=A-'a'; b=B-'1'; c=C-'a'; d=D-'1'; if(a==c&&b==d) { printf("To get from %c%c to %c%c takes 0 knight moves.\n",A,B,C,D); continue; } bfs(); } }