题解 | #走迷宫#

走迷宫

https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64

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

const int N = 1010;
char g[N][N];
int d[N][N];
int n, m;

typedef pair<int, int> PII;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

int bfs(int x1, int y1, int x2, int y2)
{
    queue<PII> q;
    q.push({x1, y1});
    memset(d, -1, sizeof d);
    d[x1][y1] = 0;

    while (!q.empty())
    {
        auto t = q.front();
        q.pop();

        if (t.first == x2 && t.second == y2)
            break;

        for (int i = 0; i < 4; i++)
        {
            int x = t.first + dx[i];
            int y = t.second + dy[i];

            if (x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] == '.' && d[x][y] == -1)
            {
                d[x][y] = d[t.first][t.second] + 1;
                q.push({x, y});
            }
        }
    }
    return d[x2][y2];
}

int main()
{
    int x1, x2, y1, y2;
    cin >> n >> m;
    cin >> x1 >> y1 >> x2 >> y2;

    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> g[i][j];

    cout << bfs(x1, y1, x2, y2) << endl;

    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务