【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;
    }
};
相关推荐
灵感__idea8 分钟前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
学习2年半41 分钟前
小米笔试题:一元一次方程求解
算法
MATLAB代码顾问44 分钟前
MATLAB绘制多种混沌系统
人工智能·算法·matlab
极客BIM工作室1 小时前
演化搜索与群集智能:五种经典算法探秘
人工智能·算法·机器学习
qq_574656251 小时前
java-代码随想录第66天|Floyd 算法、A * 算法精讲 (A star算法)
java·算法·leetcode·图论
金融街小单纯2 小时前
从蓝军建设中学习颠覆性质疑思维
人工智能·算法·机器学习
少许极端3 小时前
算法奇妙屋(五)-链表
数据结构·算法·链表
XISHI_TIANLAN3 小时前
【多模态学习】Q&A6: 什么是MOE架构?Router Z Loss函数是指什么?负载均衡损失(Load Balancing Loss)又是什么?
学习·算法·语言模型
木子.李3473 小时前
数据结构-算法C++(额外问题汇总)
数据结构·c++·算法
花心蝴蝶.4 小时前
API签名认证算法全解析
算法