LeetCode 994. 腐烂的橘子

文章介绍了如何使用广度优先搜索算法解决LeetCode上的腐烂的橘子问题,通过队列操作更新网格中橘子的状态并计算未腐烂的橘子数量。
摘要由CSDN通过智能技术生成

994. 腐烂的橘子icon-default.png?t=N7T8https://leetcode.cn/problems/rotting-oranges/description/?envType=study-plan-v2&envId=top-100-liked广度优先遍历就完事儿~,最后的判断还有没有好橘子还能优化下,但问题不大。

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        queue<pair<int, int>> rotten_oranges;
        for (int i=0; i < grid.size(); ++i) {
            for (int j=0; j < grid[0].size(); ++j) {
                if (grid[i][j] == 2) rotten_oranges.push({i, j});
            }
        }

        int res = 0;
        queue<pair<int, int>> temp;
        while (!rotten_oranges.empty()) {
            while (!rotten_oranges.empty()) {
                int i = rotten_oranges.front().first;
                int j = rotten_oranges.front().second;
                rotten_oranges.pop();
                if (i +1<grid.size() && grid[i+1][j] == 1) {
                    temp.push({i+1, j});
                    grid[i+1][j] = 2;
                }
                if (i -1 >= 0 && grid[i-1][j] == 1) {
                    temp.push({i-1, j});
                    grid[i-1][j] = 2;
                }
                if (j + 1< grid[0].size() && grid[i][j+1] == 1) {
                    temp.push({i, j+1});
                    grid[i][j+1] = 2;
                }
                if (j - 1 >=0 && grid[i][j-1] == 1) {
                    temp.push({i, j-1});
                    grid[i][j-1] = 2;
                }
            }
            if (temp.empty()) break;

            while (!temp.empty()) {
                int i = temp.front().first;
                int j = temp.front().second;
                temp.pop();
                rotten_oranges.push({i, j});
            }
            res ++;
        }
        for (vector<int> rows: grid) {
            for (int i: rows) {
                if (i == 1) return -1;
            }
        }
        return res;

    }
};

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值