HDU-1372 Knight Moves (BFS)
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.
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
University of Ulm Local Contest 1996
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 int visit[10][10]; 6 int x1,y1,x2,y2; 7 int dir[8][2]={{-2,-1},{-2,1},{-1,2},{-1,-2}, 8 {2,-1},{2,1},{1,2},{1,-2}}; 9 struct node 10 { 11 int x,y; 12 int step; 13 }; 14 int BFS(int step) 15 { 16 if(x1==x2&&y1==y2) 17 return step; 18 int i,x,y,s; 19 queue<node> q; 20 node top,temp; 21 top.x=x1,top.y=y1,top.step=0; 22 q.push(top); 23 while(!q.empty()) 24 { 25 top=q.front(); 26 q.pop(); 27 for(i=0;i<8;i++) 28 { 29 x=top.x+dir[i][0]; 30 y=top.y+dir[i][1]; 31 s=top.step; 32 if(x>0&&y>0&&x<=8&&y<=8&&visit[x][y]==0) 33 { 34 visit[x][y]=1; 35 ++s; 36 if(x==x2&&y==y2) 37 return s; 38 temp.x=x; 39 temp.y=y; 40 temp.step=s; 41 q.push(temp); 42 } 43 } 44 } 45 return -1; 46 } 47 int main() 48 { 49 char str1[3],str2[3],t; 50 while(~scanf("%s%s",str1,str2)) 51 { 52 memset(visit,0,sizeof(visit)); 53 x1=str1[0]-'a'+1; 54 y1=str1[1]-'0'; 55 x2=str2[0]-'a'+1; 56 y2=str2[1]-'0'; 57 visit[x1][y1]=1; 58 t=BFS(0); 59 printf("To get from %s to %s takes %d knight moves.\n",str1,str2,t); 60 } 61 return 0; 62 }