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

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

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

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

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

复制代码
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;
    }
};
相关推荐
yi.Ist20 分钟前
2025CCPC郑州邀请赛
c++·学习·算法·acm
少许极端30 分钟前
算法奇妙屋(四十八)-单调栈
java·算法·单调栈
水木流年追梦42 分钟前
CodeTop Top 300 热门题目2-最长回文子串
开发语言·人工智能·python·算法·leetcode
图码42 分钟前
递归入门:从n到1的优雅打印之旅
数据结构·c++·算法·青少年编程·java-ee·逻辑回归·python3.11
大肥羊学校懒羊羊42 分钟前
题解:计算约数个数
数据结构·c++·算法
生信之灵1 小时前
拓扑与曲率双剑合璧:scGeom如何从单细胞数据中“看见”细胞命运
人工智能·深度学习·算法·单细胞·多组学
良木生香1 小时前
【C++初阶】:STL——String从入门到应用完全指南(3)
c语言·开发语言·数据结构·c++·算法
_深海凉_1 小时前
LeetCode热题100-在排序数组中查找元素的第一个和最后一个位置
算法·leetcode·职场和发展
qyzm1 小时前
Educational Codeforces Round 189 (Rated for Div. 2)
数据结构·python·算法
fox_lht1 小时前
8.3.使用if let和let else实现简明的程序流控制
开发语言·后端·算法·rust