【AcWing】1076. 迷宫问题

https://www.acwing.com/problem/content/1078/

思路:当边权都相等时,可以用bfs寻找最短路。记录路径也很重要,因为第一次搜索到的一定是最短的,所以我们可以开一个二维数组记录每个点的前一个状态是什么,然后从终点搜索起点,这样从起点开始输出就是路径啦。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn = 1010;

typedef struct
{
   int x, y; 
}P;

int a[maxn][maxn], n;
P p[maxn][maxn];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};

void bfs()
{
    queue<P> q;
    q.push({n - 1, n - 1});
    
    while(q.size())
    {
        P t = q.front();
        q.pop();
        for(int i = 0;i < 4; i++)
        {
            int xx = t.x + dx[i];
            int yy = t.y + dy[i];
            if(xx >= 0 && xx < n && yy >= 0 && yy < n && a[xx][yy] == 0)
            {
                q.push({xx, yy});
                p[xx][yy] = t;
                a[xx][yy] = 1;
            }
        }
    }
    
}

int main()
{
    scanf("%d", &n);
    for(int i = 0;i < n; i++)
        for(int j = 0;j < n; j++)
            scanf("%d", &a[i][j]);
            
    bfs();
    
    P ans = {0, 0};
    
    while(true)
    {
        printf("%d %d\n", ans.x, ans.y);
        if(ans.x == n - 1 && ans.y == n - 1) break;
        ans = p[ans.x][ans.y];
    }
    
    return 0;
}在这里插入代码片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值