题解 | #走迷宫#

走迷宫

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

#include <iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
char g[N][N];
int d[N][N];
int x1, y1, x2, y2;
int n, m;
int bfs(){
    queue<PII> q;
    memset(d, -1, sizeof d);
    d[x1][y1] = 0;
    q.push({x1, y1});
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    while(q.size()){
        auto t = q.front();
        q.pop();
        for(int i = 0; i < 4; i ++){
            int x = t.first + dx[i], y = t.second + dy[i];
            if(x < n && y < m && x >= 0 && y >= 0 && 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() {
    cin >> n >> m;
    cin >> x1 >> y1 >> x2 >> y2;
    x1 --, y1 --, x2 --, y2 --;
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < m; j ++)
            cin >> g[i][j];
    cout << bfs() << endl;
    return 0;
}

全部评论

相关推荐

大清早迷迷糊糊被闹钟叫醒,坐在电脑面前开始答题,硬生生坐了2小时,要是不进面,我都无颜面对我的屁股
在看数据的傻狍子很忙碌:26届还好啦。我昨晚还要跟mt值班降级熔断的测试 , 回来做一下上周的美团笔试 , 做完已经快三点了。只a出1.25。而且手机还断网了4次五六秒,已经心碎了。
投递美团等公司10个岗位 > 美团求职进展汇总
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
02-26 16:57
明天不下雨了:把第二个项目放第一个去,其他没什么问题,多投,这世道就这样
点赞 评论 收藏
分享
coffrar:全都是已读😅沟通一千五百多个了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务