前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode热题100】【图论】腐烂的橘子

【LeetCode热题100】【图论】腐烂的橘子

作者头像
叶茂林
发布2024-04-20 11:07:27
920
发布2024-04-20 11:07:27
举报

题目描述:994. 腐烂的橘子 - 力扣(LeetCode)

腐烂的橘子会污染周围的橘子,要求多少轮扩散才能把全部橘子污染,这就相当于滴墨水入清水,会扩散,其实就是广度遍历,看看遍历多少层可以遍历完可以遍历的

先遍历一次橘子,记录下腐烂橘子的位置和新鲜橘子的数目,然后广度遍历腐烂橘子并向外扩散污染新鲜橘子

注意向外扩散时需要每次取位置,因为移动会改变位置,位置需要重置

代码语言:javascript
复制
class Solution {
public:
    int rows, columns;
    vector<vector<int> > grid;

    bool isValid(int x, int y) {
        return x >= 0 && y >= 0 && x < rows && y < columns;
    }

    int orangesRotting(vector<vector<int> > &grid) {
        rows = grid.size();
        columns = grid[0].size();
        this->grid = move(grid);
        int ans = 0, fresh = 0;
        queue<pair<int, int> > pullte;
        for (int i = 0; i < rows; ++i)
            for (int j = 0; j < columns; ++j)
                if (this->grid[i][j] == 1)
                    ++fresh;
                else if (this->grid[i][j] == 2)
                    pullte.emplace(i, j);
        int move[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        while (fresh > 0 && !pullte.empty()) {
            int scale = pullte.size();
            while (--scale >= 0) {
                for (int i = 0; i < 4; ++i) {
                    auto [x,y] = pullte.front();
                    x += move[i][0];
                    y += move[i][1];
                    if (isValid(x, y) && this->grid[x][y] == 1) {
                        this->grid[x][y] = 2;
                        pullte.emplace(x, y);
                        --fresh;
                    }
                }
                pullte.pop();
            }
            ++ans;
        }
        if (fresh > 0)
            return -1;
        return ans;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-04-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档