poj2241Knight Moves
出自http://poj.org/problem?id=2243
题意:给定两个位置a和b,计算马从a都的最小步骤,BFS搜索。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #define MAX 10 6 using namespace std; 7 int dir[8][2]={{-1,2},{1,2},{1,-2},{-1,-2},{2,1},{-2,1},{-2,-1},{2,-1}}; 8 struct point{ 9 int x, y; 10 }start, end; 11 int step[MAX][MAX]; 12 int visit[MAX][MAX]; 13 queue<point> Q; 14 int BFS() 15 { 16 while(!Q.empty()){ 17 Q.pop(); 18 } 19 Q.push(start); 20 visit[start.x][start.y] = 1; 21 22 while(!Q.empty()){ 23 point temp = Q.front(); 24 Q.pop(); 25 for(int i = 0; i < 8; i++) 26 { 27 int dx = temp.x+dir[i][0]; 28 int dy = temp.y+dir[i][1]; 29 if(dx>=1&&dx<=8&&dy>=1&&dy<=8&&!visit[dx][dy]){ 30 step[dx][dy] = step[temp.x][temp.y]+1; 31 visit[dx][dy] = 1; 32 if(dx==end.x && dy==end.y) 33 break; 34 point next; 35 next.x=dx; 36 next.y=dy; 37 Q.push(next); 38 } 39 } 40 } 41 return step[end.x][end.y]; 42 43 } 44 int main() 45 { 46 47 char c1, c2; 48 while(cin >> c1 >> start.x >> c2 >> end.x){ 49 start.y = (int)(c1-'a'+1); 50 end.y = (int)(c2-'a'+1); 51 memset(visit, 0, sizeof(visit)); 52 memset(step, 0, sizeof(step)); 53 int ans = BFS(); 54 printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,start.x,c2,end.x,ans); 55 56 } 57 return 0; 58 }