定义一个二维数组:
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 <iostream>
#include <queue>
#include <cstdio>
using namespace std;
const int N = 110;
char g[N][N];
bool vis[N][N];int dx[] = {0, 0, 1, -1};int dy[] = {1, -1, 0, 0};struct node {int x, y;int step;int path[105][3];
};void bfs() {queue<node>q;int sx = 0, sy = 0;int ex = 4, ey = 4;node start;start.x = sx;start.y = sy;start.step = 0;start.path[0][0] = sx;start.path[0][1] = sy;vis[0][0] = true;q.push(start);while (q.size()) {node t = q.front();q.pop();if (t.x == ex && t.y == ey) {for (int i = 0; i < t.step; i++) {printf("(%d, %d)\n", t.path[i][0], t.path[i][1]);}cout << "(4, 4)" << endl;}for (int i = 0; i < 4; i++) {int xx = t.x + dx[i];int yy = t.y + dy[i];if (xx < 0 || xx > 4 || yy < 0 || yy > 4)continue;if (vis[xx][yy] || g[xx][yy] == '1')continue;node next;next = t;next.x = xx;next.y = yy;next.step = t.step + 1;next.path[next.step][0] = xx;next.path[next.step][1] = yy;vis[xx][yy] = true;q.push(next);}}
}int main() {for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++)cin >> g[i][j];bfs();return 0;
}