|
Knight MovesTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11823 Accepted Submission(s): 6962
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.
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
Sample Output
Source
这题用dfs和bfs都可以;
题目的意思:从x,y到达ax,ay的最小步数,走的是马的步子,也就是走日子步;
这里用bfs加dp来写
用dp【i】【j】表示从x,y到i,j的最小步数;
using namespace std ; int c[]={ -1 , 1 , 2 , -2 , -1 , 1 , 2 , -2 }; int b[]={ 2 , -2 , -1 , 1 , -2 , 2 , 1 , -1 }; struct node{ int x; int y; }; queue <node>q; bool visit[ 200 ][ 200 ];//访问标志 int ax,ay; int sum= 0 ; int dp[ 200 ][ 200 ]; char e[ 12 ],r[ 12 ]; voidbfs(int x,int y) { if (x==ax&&ay==y) { cout << "To get from " <<e<< " to " <<r<< " takes 0 knight moves." << endl ; return ; } node a; a.x=x;a.y=y; q.push(a); while (!q.empty()) { sum++; x=q.front().x; y=q.front().y; visit[x][y]= true ; q.pop(); int i; for (i= 0 ;i< 8 ;i++) { int nx=x+c[i]; int ny=y+b[i]; a.x=nx; a.y=ny; if (a.x>= 1 &&a.x<= 8 &&a.y>= 1 &&a.y<= 8 &&!visit[nx][ny]) { dp[nx][ny]=min(dp[x][y]+ 1 ,dp[nx][ny]); q.push(a); } } } cout << "To get from " <<e<< " to " <<r<< " takes " ; cout <<dp[ax][ay]<< " knight moves." << endl ; } intmain() { int x,y; while ( cin >>e>>r) { memset (visit, false , sizeof (visit)); x=e[ 0 ]- 'a' + 1 ; y=e[ 1 ]- '0' ; ax=r[ 0 ]- 'a' + 1 ; ay=r[ 1 ]- '0' ; int i,j; for (i= 0 ;i<= 20 ;i++) { for (j= 0 ;j<= 20 ;j++) { dp[i][j]= 100 ; } } dp[x][y]= 0 ; bfs(x,y); } return 0 ; }
人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想。
|