01迷宫(输出路线)

链接: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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值