链接:01迷宫
来源:牛客网
题目描述
给出一个01迷宫,'0’代表空地,'1’代表墙 。
输出起点到终点的最短路的长度及路径。
规定:为了保证答案唯一,总会按照下(D),上(U),左(L),右®的优先级行走。
假设当前点为(x, y),规定方向如下:
D:(x, y) -> (x, y+1)
U:(x, y) ->(x, y-1)
L:(x, y) ->(x-1, y)
R:(x, y) ->(x+1, y)
输入描述:
第一行两个整数n,m,代表迷宫的长和宽。
接下来n行,每行是一个长度为m的01串
接下来一行四个整数sx,sy,ex,ey。分别代表起点坐标和终点的坐标。
输出描述:
若存在最短路则按照题目描述输出最短路径,否则打印-1.
示例1
2 2
00
00
1 1 2 2
说明
备注:
1 ≤ n,m ≤ 500
思路:
BFS+路径记录。可能起点或者终点就是障碍,那么直接输出-1,也可能起点就是终点,输出0和一个空串。
#include <bits/stdc++.h>
using namespace std;
int n,m;
char a[510][510],pre[510][510];
int vis[510][510];
string nec = "DULR";
int ne[4][2] = {0, 1, 0, -1, -1, 0, 1, 0};
int sx,sy,ex,ey,dis = -1;
int tx,ty;
struct xx {
int x,y,step;
}u;
void bfs() {
if(a[sx][sy] == '1' || a[ex][ey] == '1') return;
queue<xx> q;
q.push({sx,sy,0});
vis[sx][sy] = 1;
while (!q.empty()) {
u = q.front();
q.pop();
if(u.x == ex && u.y == ey) { dis = u.step; break; }
for (int i = 0;i < 4;i++) {
tx = ne[i][0] + u.x;
ty = ne[i][1] + u.y;
if (tx > 0 && tx <= n && ty > 0 && ty <= m && !vis[tx][ty] && a[tx][ty] == '0') {
vis[tx][ty] = 1;
q.push({tx, ty, u.step+1});
pre[tx][ty] = nec[i];
}
}
}
}
void Print() { //逆序输出路径
if(dis == -1) {
cout << -1; return ;
}
string res = "";
tx = ex; ty = ey;
int i;
while(tx != sx || ty != sy) {
res += pre[tx][ty];
i = nec.find(pre[tx][ty]);
tx -= ne[i][0]; ty -= ne[i][1];
}
reverse(res.begin(), res.end());
cout << dis << "\n" << res << "\n";
}
int main() {
cin >> n >> m;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
cin >> a[i][j];
}
}
cin >> sx >> sy >> ex >> ey;
memset(pre, '0', sizeof(pre));
bfs();
Print();
return 0;
}