题目地址:
https://www.acwing.com/problem/content/1078/
给定一个 n × n n×n n×n的二维数组,如下所示:
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 1 1表示墙壁, 0 0 0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。数据保证至少存在一条从左上角走到右下角的路径。
输入格式:
第一行包含整数 n n n。接下来 n n n行,每行包含 n n n个整数 0 0 0或 1 1 1,表示迷宫。
输出格式:
输出从左上角到右下角的最短路线,如果答案不唯一,输出任意一条路径均可。按顺序,每行输出一个路径中经过的单元格的坐标,左上角坐标为 ( 0 , 0 ) (0,0) (0,0),右下角坐标为 ( n − 1 , n − 1 ) (n−1,n−1) (n−1,n−1)。
数据范围:
0 ≤ n ≤ 1000 0≤n≤1000 0≤n≤1000
边权都是 1 1 1,可以用BFS来求最短路,同时用一个数组 p p p来存 p [ i ] [ j ] p[i][j] p[i][j]这个格子是从哪个格子走过来的。求路径的时候再由终点向起点推。为了方便,也可以直接从终点 ( n − 1 , n − 1 ) (n-1,n-1) (n−1,n−1)开始搜,搜到起点 ( 0 , 0 ) (0,0) (0,0)为止,这样反推出路径的时候就是恰好从 ( 0 , 0 ) (0,0) (0,0)出发的了。代码如下:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1010, d[] = {
1, 0, -1, 0, 1};
int n;
int a[N][N];
pair<int, int> pre[N][N];
queue<pair<int, int> > q;
void bfs(int x, int y) {
q.push({
x, y});
// 未访问的点设为-1
memset(pre, -1, sizeof pre);
pre[x][y] = {
x, y};
while (!q.empty()) {
auto t = q.front();
q.pop();
x = t.first, y = t.second;
for (int i = 0; i < 4; i++) {
int nx = x + d[i], ny = y + d[i + 1];
// 出界了,略过
if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
// 略过障碍物
if (a[nx][ny]) continue;
// 访问过,则略过
if (pre[nx][ny].first != -1) continue;
q.push({
nx, ny});
pre[nx][ny] = t;
// 搜到起点了,可以直接退出
if (nx == 0 && ny == 0) return;
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
bfs(n - 1, n - 1);
pair<int, int> end = {
0, 0};
while (1) {
printf("%d %d\n", end.first, end.second);
if (end.first == n - 1 && end.second == n - 1) break;
end = pre[end.first][end.second];
}
return 0;
}
时空复杂度 O ( n 2 ) O(n^2) O(n2)。