HDU ACM 1372 Knight Moves (BFS)
http://acm.hdu.edu.cn/showproblem.php?pid=1372
题意:求一匹马从1个位置走到一个位置所需要的步数,这匹马是走'日'字型的(类似中国象棋的马)
输入:a1 b2 a表示第一行, 1表示第一列 以此类推 行的范围为a~h 列的范围为1~8
输出:To get from (起点) to (终点) takes (多少步) knight moves.
简单的BFS(),连障碍都没有.
只要知道马的前进方法就没什么难度.
主要问题还是理解题意啊 囧
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "iostream" 2 #include "queue" 3 using namespace std; 4 struct Node 5 { 6 int x; 7 int y; 8 int step; 9 }; 10 int point[8][2]= {1,2,-1,2,1,-2,-1,-2,2,1,-2,1,2,-1,-2,-1}; 11 int used[10][10]; 12 char s_ch,e_ch; 13 Node s,e; 14 int BFS(Node a,Node b) 15 { 16 memset(used,0,sizeof(used)); 17 queue <Node> q; 18 a.step = 0; 19 q.push(a); 20 while(!q.empty()) 21 { 22 Node mid; 23 mid = q.front(); 24 if(b.x == mid.x && b.y == mid.y) 25 { 26 cout<<"To get from "<<s_ch<<s.y<<" to "<<e_ch<<e.y<<" takes "<<mid.step<<" knight moves."<<endl; 27 return 1; 28 } 29 q.pop(); 30 int i; 31 for(i=0;i<8;i++) 32 { 33 a.x = mid.x + point[i][0]; 34 a.y = mid.y + point[i][1]; 35 a.step = mid.step; 36 if(!used[a.x][a.y] && a.x >=1 && a.y >=1 && a.x <= 8 && a.y <= 8) 37 { 38 a.step++; 39 used[a.x][a.y] = 1; 40 q.push(a); 41 } 42 } 43 } 44 } 45 46 int main() 47 { 48 while(cin>>s_ch>>s.y>>e_ch>>e.y) 49 { 50 s.x = s_ch - 'a' + 1; 51 e.x = e_ch - 'a' + 1; 52 BFS(s,e); 53 } 54 return 0; 55 }