UVA - 439 Knight Moves
2016-08-11 20:27
363 查看
题目大意:8×8 棋盘内,问从一个点到另一个点要走几步。移动方式是国际象棋中骑士的移动方式:先上下左右移动一格,然后斜着移动一格,即在一个 2×3 的格子内从一角移动到另一角。
解题思路:大概是第一题 bfs,有点懵。把所给的位置信息转化为坐标。每移动一个合法位置就加入队列,走过的位置标记一下,到达目标返回距离就行。感觉没有题解都没法做下去,心累。
解题思路:大概是第一题 bfs,有点懵。把所给的位置信息转化为坐标。每移动一个合法位置就加入队列,走过的位置标记一下,到达目标返回距离就行。感觉没有题解都没法做下去,心累。
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; int map[10][10]; struct queue { int x; int y; int t; }; struct queue q[100]; int dd[8][2] = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}}; int bfs(int x1, int y1, int x2, int y2) { if (x1 == x2 && y1 == y2) return 0; q[0].x = x1; q[0].y = y1; q[0].t = 0; int t1 = 0, t2 = 1; while (t1 < t2) { struct queue now = q[t1++]; for (int i = 0; i < 8; i++) { x1 = now.x + dd[i][0]; y1 = now.y + dd[i][1]; if (!map[x1][y1] && x1 > 0 && x1 < 9 && y1 > 0 && y1 < 9) { if (x1 == x2 && y1 == y2) return now.t+1; q[t2].x = x1; q[t2].y = y1; q[t2++].t = now.t+1; map[x1][y1] = 1; } } } return 0; } int main() { int x1, y1, x2, y2; char ch1, ch2; while (scanf("%c%d %c%d\n", &ch1, &y1, &ch2, &y2) != EOF) { memset(map, 0, sizeof(map)); x1 = ch1 - 'a' + 1; x2 = ch2 - 'a' + 1; int ans = bfs(x1, y1, x2, y2); printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, y1, ch2, y2, ans); } return 0; }
相关文章推荐
- UVa 439 - Knight Moves 搜索专题
- UVA 439 Knight Moves
- UVA 439 - Knight Moves
- UVA 439(p177)----Knight Moves
- UVa 439,Knight Moves
- 【习题 6-4 UVA-439】Knight Moves
- UVa 439 - Knight Moves
- UVA439 POJ2243 HDU1372 ZOJ1091 Knight Moves
- UVa 439 - Knight Moves
- Uva - 439 - Knight Moves
- UVA - 439 Knight Moves
- Knight Moves - UVa 439 搜索
- UVA_439 Knight Moves
- UVa 439 Knight Moves
- Uva - 439 - Knight Moves
- uva 439 - Knight Moves
- UVA-439 Knight Moves
- UVA439 - Knight Moves
- UVA - 439 - Knight Moves (BFS)
- Uva 439 Knight Moves