HDU 1372 Knight moves
阿新 • • 發佈:2018-11-26
題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1372
Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14208 Accepted Submission(s): 8306
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. 題意:在一個 8 × 8 的網格中,給你兩個點,按馬行日的方法走,求走的最短步數,注意下輸出的格式,別隻輸出了結果沒有輸出那句話。。。
注意:馬走日,有八個方向!
1 #include<iostream> 2 #include<queue> 3 #include<cstdio> 4 #include <cstring> 5 6 using namespace std; 7 8 int go[8][2] = {1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2}; 9 char s1[3],s2[3]; 10 int sx,sy,ex,ey; 11 bool mark[10][10]; 12 struct node 13 { 14 intAc程式碼x,y; 15 int step; 16 }; 17 18 void bfs() 19 { 20 queue<node> q; 21 struct node cu,ne; 22 cu.x = sx; 23 cu.y = sy; 24 cu.step =0; 25 mark[cu.x][cu.y] = 1; //別忘了標記,雖然本題不標記也可以; 26 q.push(cu); 27 while(!q.empty()) 28 { 29 cu = q.front(); 30 q.pop();31 if(cu.x == ex && cu.y == ey) 32 { 33 printf("To get from %s to %s takes %d knight moves.\n",s1,s2,cu.step); 34 return ; 35 } 36 for(int i=0;i<8;i++) 37 { 38 ne.x = cu.x + go[i][0]; 39 ne.y = cu.y + go[i][1]; 40 if(ne.x>=0&&ne.x<8&&ne.y>=0&&ne.y<8&&!mark[ne.x][ne.y]) //注意這個範圍是0--7的; 41 { 42 ne.step = cu.step + 1; 43 mark[ne.x][ne.y] = 1; 44 q.push(ne); 45 } 46 } 47 } 48 } 49 int main() 50 { 51 //也可以用字母加數字的方式輸入。eg while(scanf("%c%d %c%d",&c1,&d1,&c2,&d2),但別忘了輸出也是字母加數字 52 while(scanf("%s%s",s1,s2)!=EOF) //這兩個%s之間的空格有沒有都可以 53 { 54 //a--h 和 1--8 數量是一樣的,所以,a--h減'a'相當於0--7,所以,數字別忘了減 1 ; 55 sx = s1[0] - 'a'; 56 sy = s1[1] - '1'; 57 ex = s2[0] - 'a'; 58 ey = s2[1] - '1'; 59 memset(mark,0,sizeof(mark)); 60 bfs(); 61 memset(s1,0,sizeof(s1)); 62 memset(s2,0,sizeof(s2)); 63 } 64 return 0; 65 }