HDU1372:Knight Moves(BFS) 解题心得
原题:
我的代码 :
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string.h> 5 #include<queue> 6 using namespace std; 7 8 9 struct point 10 { 11 int x; 12 int y; 13 int step; 14 point () 15 { 16 x = 0; 17 y = 0; 18 step = 0; 19 } 20 21 bool operator ==(point &b) 22 { 23 return (x == b.x&&y == b.y); 24 } 25 }first,target; 26 27 int times[8][8]; 28 29 int directionX[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; 30 int directionY[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 31 32 33 bool check(point &p) 34 { 35 if (p.x<0 || p.y<0 || p.x>7 || p.y>7 ) 36 { 37 return 0; 38 } 39 if (times[p.x][p.y] != 0) 40 { 41 return 0; 42 } 43 return 1; 44 } 45 46 int bfs(point & first) 47 { 48 queue<point> q; 49 times[first.x][first.y]++; 50 q.push(first); //因为没有到终点,所以加入搜索队列 51 while(!q.empty()) 52 { 53 point cur = q.front(); //cur 是当前的对象 54 q.pop(); 55 point temp; //构建当前对象副本 56 for (int i = 0; i < 8; i++) 57 { 58 //进行变换 59 temp.x = cur.x + directionX[i]; 60 temp.y = cur.y + directionY[i]; 61 //变换结束,检查 62 if (!check(temp)) continue; 63 if (temp == target) return cur.step+1; 64 times[temp.x][temp.y]++; 65 temp.step = cur.step + 1; 66 q.push(temp); 67 } 68 } 69 return -1; 70 71 72 } 73 74 int main() 75 { 76 char x1, x2, y1, y2; 77 int min; 78 while (cin >> x1>>y1) 79 { 80 cin >> x2 >> y2; 81 first.x = x1 - 'a'; 82 first.y = y1-'1'; 83 target.x = x2 - 'a'; 84 target.y = y2-'1'; 85 if (first == target) 86 { 87 min = 0; 88 } 89 else 90 { 91 memset(times, 0, sizeof(times)); 92 min = bfs(first); 93 } 94 printf("To get from %c%c to %c%c takes %d knight moves.\n",x1, y1,x2, y2, min); 95 } 96 97 return 0; 98 }