Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5296 Accepted Submission(s): 3234
Problem Description
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.
Input
The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
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.
Source
Recommend
1 //46MS 288K 1018 B C++ 2 /* 3 4 题意: 5 在8*8的棋盘上问在初始位置最少移动多少步能到指定位置 6 7 BFS: 8 基础的BFS.移动像象棋的马一样,每一步最多有八个选择 9 10 */ 11 #include<iostream> 12 #include<queue> 13 using namespace std; 14 struct node{ 15 int x,y,cnt; 16 }; 17 int g[10][10]; 18 int vis[10][10]; 19 int mov[8][2]={1,2,2,1,-1,2,2,-1,1,-2,-2,1,-1,-2,-2,-1}; 20 int sx,sy,ex,ey; 21 int bfs() 22 { 23 queue<node>Q; 24 memset(vis,0,sizeof(vis)); 25 node t={sx,sy,0}; 26 vis[sx][sy]=1; 27 Q.push(t); 28 while(!Q.empty()){ 29 t=Q.front(); 30 Q.pop(); 31 if(t.x==ex && t.y==ey) return t.cnt; 32 for(int i=0;i<8;i++){ 33 node tt=t; 34 tt.cnt++; 35 tt.x+=mov[i][0]; 36 tt.y+=mov[i][1]; 37 if(tt.x>0&&tt.x<=8 && tt.y>0&&tt.y<=8 && !vis[tt.x][tt.y]){ 38 Q.push(tt); 39 vis[tt.x][tt.y]=1; 40 } 41 } 42 } 43 } 44 int main(void) 45 { 46 char s[5],e[5]; 47 while(cin>>s>>e) 48 { 49 sx=s[0]-'a'+1; 50 sy=s[1]-'0'; 51 ex=e[0]-'a'+1; 52 ey=e[1]-'0'; 53 printf("To get from %s to %s takes %d knight moves. ",s,e,bfs()); 54 } 55 return 0; 56 }