LeetCode 994. 腐烂的橘子(bfs)

链接:https://leetcode-cn.com/problems/rotting-oranges/
来源:LeetCode

在这里插入图片描述在这里插入图片描述在这里插入图片描述  思路:先判断给出的图中是否有新鲜的橘子,如果没有就输出 0,其次用 b f s bfs bfs 求出每个腐烂的橘子到其邻近新鲜橘子的距离(优先队列每次取出最小的花费的点去更新其他点的距离)。实现 b f s bfs bfs 的时候注意代码不要写错(执行出错一般是因为数组越界)。

class Solution {
public:
    struct Node {
        int x, y, cost;
        Node(){}
        Node(int x, int y, int cost) : x(x), y(y), cost(cost) {}
        bool operator < (const Node & node) const {
            return cost > node.cost;
        }
    };
    void bfs(vector<vector<int>>& grid, vector<vector<int>>& step) {
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> vis(n, vector<int>(m, false));
        int net[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        priority_queue<Node>pq;
        for (int i = 0; i < n; i ++) {
            for(int j = 0; j < m; j ++) {
                if (grid[i][j] == 2) pq.push(Node(i, j, 0));
            }
        }
        while (!pq.empty()) {
            Node now = pq.top(); pq.pop();
            if (vis[now.x][now.y]) continue;
            step[now.x][now.y] = now.cost;
            vis[now.x][now.y] = true;
            for (int i = 0; i < 4; i ++) {
                int netx = now.x + net[i][0];
                int nety = now.y + net[i][1];
                if (netx < 0 || netx >= n || nety < 0 || nety >= m) 
                	continue;
                if (grid[netx][nety] == 0 ) vis[netx][nety] = true;
                if (vis[netx][nety]) continue;
                if (grid[netx][nety] == 1) {
                    pq.push(Node(netx, nety, now.cost + 1));
                } else if (grid[netx][nety] == 2) {
                    pq.push(Node(netx, nety, 0));
                }
            }
        }
    }
    int orangesRotting(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size();
        int cnt1 = 0;
        for (int i = 0; i < n; i ++) {
            for(int j = 0; j < m; j ++) {
                if (grid[i][j] == 1) cnt1 ++;
            }
        }
        if (cnt1 == 0) return 0;
        vector<vector<int>> step(n, vector<int>(m, 0));
        bfs(grid, step);
        int Max = -1;
        bool flag = false;
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                if (grid[i][j] == 1 && step[i][j] == 0) {
                    flag = true;
                    break;
                }
                if (Max < step[i][j]) Max = step[i][j];
            }
        }
        if (flag) Max = -1;
        return Max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值