题解 | 走格子

走格子

https://www.nowcoder.com/practice/365493766c514d0da0cd774d3d40fd49

#include <array>
#include <queue>
#include <vector>
class Flood {
  public:
    int floodFill(vector<vector<int> > map, int n, int m) {
        // write code here
        vector<vector<bool>>vis(n, vector<bool>(m, false));
        int step = 0;
        queue<pair<int, int>> pos;
        pos.push({0, 0});
        array<int, 4> dx = {1, 0, -1, 0};
        array<int, 4>dy = {0, 1, 0, -1};

        while (!pos.empty()) {
            int sz = pos.size();
            while (sz--) {
                auto [x, y] = pos.front();
                if (x == n - 1 && y == m - 1) return step;
                pos.pop();
                for (int i = 0; i < 4; ++i) {
                    int nx = x + dx[i];
                    int ny = y + dy[i];
                    if (nx >= 0 && nx < n && ny >= 0 && ny < m && map[nx][ny] == 0 &&
                            !vis[nx][ny]) {
                        pos.push({nx, ny});
                        vis[nx][ny] = true;
                    }
                }
            }
            ++step;

        }
        return -1;
    }
};

#BFS#
全部评论

相关推荐

07-18 15:02
门头沟学院 Java
刚打开网申页面就不想填了,还是不要为难自己了
poppinzhan...:多益老行业毒瘤了,碰到徐波这种恶心的烂人,去了也是受罪。
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
07-15 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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