题目
【题目描述】
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
【输入】
一个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
【输出样例】
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
思路
使用广搜,每扩展一步,就记录这一步的前驱,最后递归输出
代码
#include<iostream>
#include<queue>
using namespace std;
const int N = 5;
struct Node {
int x, y;
};
queue<Node> q;
Node pre[N][N];
int g[N][N], dir[4][2] = { -1,0,0,1,1,0,0,-1 };
bool st[N][N];
// 将(x,y)入队并标记,记录(x,y)的前驱是(tx,ty)
void push(int x, int y, int tx, int ty) {
Node node = { x,y };
q.push(node);
st[x][y] = true;
pre[x][y].x = tx;
pre[x][y].y = ty;
}
void print(int x, int y) { // 输出以(x,y)结束的链
if (x == -1 && y == -1) return;
print(pre[x][y].x, pre[x][y].y);
cout << "(" << x << ", " << y << ")" << endl;
}
void bfs() {
push(0, 0, -1, -1); // -1代表起点的前驱
while (q.size()) {
Node t = q.front();
q.pop();
if (t.x == 4 && t.y == 4) {
print(4, 4);
break;
}
for (int i = 0; i < 4; i++) {
int nx = t.x + dir[i][0], ny = t.y + dir[i][1];
if (nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && g[nx][ny] == 0 && !st[nx][ny]) push(nx, ny, t.x, t.y);
}
}
}
int main() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) cin >> g[i][j];
bfs();
return 0;
}
评测结果