1076. 迷宫问题(bfs,记录路径)

1076. 迷宫问题 - AcWing题库

给定一个 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表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

数据保证至少存在一条从左上角走到右下角的路径。

输入格式

第一行包含整数 n。

接下来 n 行,每行包含 n 个整数 0 或 1,表示迷宫。

输出格式

输出从左上角到右下角的最短路线,如果答案不唯一,输出任意一条路径均可。

按顺序,每行输出一个路径中经过的单元格的坐标,左上角坐标为 (0,0),右下角坐标为 (n−1,n−1)

数据范围

0≤n≤1000

输入样例:
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
难度:简单
时/空限制:1s / 64MB
总通过数:14537
总尝试数:23174
来源:《信息学奥赛一本通》, kuangbin专题 , POJ3984
算法标签

 解析:

使用bfs搜索,同时使用数组pre记录当前点的最短路径得上一个点是哪个点

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

using namespace std;
typedef long long LL;
typedef pair PII;
const int N = 1e3 + 5;
int n;
int arr[N][N],v[N][N];
PII pre[N][N];
int dx[4] = { 0,0,-1,1 }, dy[4] = { -1,1,0,0 };


void bfs() {
	queue>q;
	q.push({ 0,0 });
	v[0][0] = 1;
	while (!q.empty()) {
		pairt = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int a = t.first + dx[i], b = t.second + dy[i];
			if (a < 0 || a >= n || b < 0 || b >= n)continue;
			if (v[a][b]||arr[a][b]==1)continue;
			q.push({ a,b });
			v[a][b] = 1;
			pre[a][b] = t;
		}
	}
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%d", &arr[i][j]);
		}
	}
	bfs();
	stackstk;
	PII t = { n - 1,n - 1 };
	stk.push(t);
	while (t.first || t.second ) {
		t = pre[t.first][t.second];
		stk.push(t);
	}
	while (!stk.empty()) {
		printf("%d %d\n", stk.top().first, stk.top().second);
		stk.pop();
	}
	return 0;
}

你可能感兴趣的:(图论:搜索,宽度优先,算法)