题目大意:
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
#include <cstdio> #include <cstring> int array[5][5]; int vis[5][5]; int dir[4][2] = {1,0,0,1,-1,0,0,-1}; struct node { int x, y; int pre; }; node que[100]; void print(node s) { if (s.pre != -1)print(que[s.pre]); printf("(%d, %d)\n", s.x, s.y); } void bfs() { memset(vis, 0, sizeof(vis)); int front = 0, end = 0; node s, t, next; s.x = 0, s.y = 0, s.pre = -1; vis[0][0] = 1; que[end++] = s; while (front < end) { t = que[front]; front++; if (t.x == 4 && t.y == 4) { print(t); return; } for (int i = 0; i < 4; i++) { int nx = t.x + dir[i][0]; int ny = t.y + dir[i][1]; if (nx < 0 || nx >= 5 || ny < 0 || ny >= 5 || array[nx][ny] == 1)continue; else if (!vis[nx][ny]) { vis[nx][ny] = 1; next.x = nx, next.y = ny; next.pre = front - 1; que[end++] = next; } } } } int main() { int i, j; for (i = 0; i < 5; i++) for (j = 0; j < 5; j++) scanf("%d", &array[i][j]); bfs(); return 0; }
2018-03-31