在迷宫里使用魔法BFS

题目链接

比较有趣的一个BFS,用两个队列维护。

AC代码:

#include <bits/stdc++.h>
using namespace std;

char s[1010][1010];
bool vis[1010][1010];
int mov[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};

struct node
{
    int x, y, step;
};
queue<node> q1;
queue<node> q2;
int n, m, sx, sy, ex, ey;
int bfs()
{
    q1.push(node{sx, sy, 0});
    while (q1.size())
    {
        while (q1.size())
        {
            node temp = q1.front();
            q1.pop();
            q2.push(temp);
            if (temp.x == ex && temp.y == ey)
                return temp.step;
            for (int i = 0; i < 4; i++)
            {
                int xx = temp.x + mov[i][0];
                int yy = temp.y + mov[i][1];
                if (xx < 1 || xx > n || yy < 1 || yy > m || vis[xx][yy] || s[xx][yy] == '#')
                    continue;
                q2.push(node{xx, yy, temp.step});
                q1.push(node{xx, yy, temp.step});
                vis[xx][yy] = 1;
            }
        }
        while (q2.size())
        {
            node temp = q2.front();
            q2.pop();
            for (int xx = temp.x - 2; xx <= temp.x + 2; xx++)
            {
                for (int yy = temp.y - 2; yy <= temp.y + 2; yy++)
                {
                    if (xx < 1 || xx > n || yy < 1 || yy > m || vis[xx][yy] || s[xx][yy] == '#')
                        continue;
                    q1.push(node{xx, yy, temp.step + 1});
                    vis[xx][yy] = 1;
                }
            }
        }
    }
    return -1;
}
int main()
{
    cin >> n >> m >> sx >> sy >> ex >> ey;
    for (int i = 1; i <= n; i++)
        cin >> s[i] + 1;
    cout << bfs() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hesorchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值