题解 | #走迷宫#

走迷宫

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

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

const int N = 1010;
char mpt[N][N];
int vis[N][N];
int dir[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int h, w;
int sx, sy, ex, ey;

struct Node {
    int x, y, dist;
};

int bfs() {
    queue<Node> q;
    q.push({sx, sy, 0});
    vis[sx][sy] = 1;

    while (!q.empty()) {
        Node now = q.front();
        q.pop();

        if (now.x == ex && now.y == ey) {
            return now.dist;
        }

        for (int i = 0; i < 4; i++) {
            int nx = now.x + dir[i][0];
            int ny = now.y + dir[i][1];
            if (nx > 0 && nx <= h && ny > 0 && ny <= w && vis[nx][ny]==0 && mpt[nx][ny] == '.') {
                vis[nx][ny] = 1;
                q.push({nx, ny, now.dist + 1});
            }
        }
    }

    return -1; // 如果队列清空还没有找到,返回-1
}

int main() {
    cin >> h >> w;
    cin >> sx >> sy >> ex >> ey;
    for (int i = 1; i <= h; i++) {
        for (int j = 1; j <= w; j++) {
            cin >> mpt[i][j];
        }
    }

    memset(vis, 0, sizeof(vis));
    int ans = bfs();
    cout << ans << endl;
    return 0;
}

全部评论

相关推荐

🎓学历背景:双非土木硕👨‍💻意向职位:AI应用开发大佬们可以帮我看看简历吗,秋招至今0offer
秋招结束再玩瓦:今年科班都不好找哇……你可以试试交叉岗,比如制造业国企的一些开发算法,或者互联网的边缘岗,it技术支持,运维这些
我的简历长这样
点赞 评论 收藏
分享
10-10 16:30
济宁学院 Java
不想做程序员:面试官:蓝桥杯三等奖?你多去两次厕所都能拿二等吧
点赞 评论 收藏
分享
牛客77743221...:做一段时间,公司出钱送你去缅甸和泰国旅游
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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