HDU 1372 Knight Moves 題解
阿新 • • 發佈:2018-11-16
Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14125 Accepted Submission(s): 8269
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.
1 //Author:LanceYu 2 #include<iostream> 3 #include<string> 4 #include<cstring> 5 #include<cstdio> 6 #include<fstream> 7 #include<iosfwd> 8 #include<sstream> 9 #include<fstream> 10 #include<cwchar> 11 #include<iomanip> 12 #include<ostream> 13 #include<vector> 14 #include<cstdlib> 15 #include<queue> 16 #include<set> 17 #include<ctime> 18 #include<algorithm> 19 #include<complex> 20 #include<cmath> 21 #include<valarray> 22 #include<bitset> 23 #include<iterator> 24 #define ll long long 25 using namespace std; 26 const double clf=1e-8; 27 //const double e=2.718281828; 28 const double PI=3.141592653589793; 29 const int MMAX=2147483647; 30 //priority_queue<int>p; 31 //priority_queue<int,vector<int>,greater<int> >pq; 32 struct node 33 { 34 int x,y,step; 35 }; 36 queue<node> q; 37 int dir[8][2]={{-2,-1},{-1,-2},{-2,1},{-1,2},{1,2},{1,-2},{2,-1},{2,1}};//馬所能夠跳的八個方向記錄下來 38 int vis[8][8]; 39 char temp[3][3];//定義一個字串用於輸入 40 int change(char c)//字元轉數字 41 { 42 switch (c) 43 { 44 case 'a':return 0; 45 break; 46 case 'b':return 1; 47 break; 48 case 'c':return 2; 49 break; 50 case 'd':return 3; 51 break; 52 case 'e':return 4; 53 break; 54 case 'f':return 5; 55 break; 56 case 'g':return 6; 57 break; 58 case 'h':return 7; 59 break; 60 case '1':return 0; 61 break; 62 case '2':return 1; 63 break; 64 case '3':return 2; 65 break; 66 case '4':return 3; 67 break; 68 case '5':return 4; 69 break; 70 case '6':return 5; 71 break; 72 case '7':return 6; 73 break; 74 case '8':return 7; 75 break; 76 } 77 } 78 int bfs(int x,int y,int x1,int y1) 79 { 80 while(!q.empty())//佇列的初始化,全部清空 81 q.pop(); 82 int i; 83 q.push(node{x,y,0}); 84 while(!q.empty()) 85 { 86 node t=q.front(); 87 q.pop(); 88 if(t.x==x1&&t.y==y1) 89 return t.step; 90 for(i=0;i<8;i++) 91 { 92 int dx=t.x+dir[i][0]; 93 int dy=t.y+dir[i][1]; 94 if(dx>=0&&dy>=0&&dx<8&&dy<8&&!vis[dx][dy])//基本搜尋 95 { 96 vis[dx][dy]=1; 97 q.push(node{dx,dy,t.step+1}); 98 } 99 } 100 } 101 return 0; 102 } 103 int main() 104 { 105 while(scanf("%s%s",temp[0],temp[1])!=EOF) 106 { 107 memset(vis,0,sizeof(vis)); 108 int x=change(temp[0][0]); 109 int y=change(temp[0][1]); 110 int x1=change(temp[1][0]); 111 int y1=change(temp[1][1]);//確定首尾點 112 int ans=bfs(x,y,x1,y1); 113 printf("To get from %s to %s takes %d knight moves.\n",temp[0],temp[1],ans);//輸出 114 } 115 return 0; 116 }
2018-11-16 00:03:31 Author:LanceYu