【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;
    }
};
相关推荐
helloworldandy11 分钟前
高性能图像处理库
开发语言·c++·算法
2401_8365631812 分钟前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy15 分钟前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao18984423 分钟前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
代码无bug抓狂人30 分钟前
动态规划(附带入门例题)
c语言·算法·动态规划
weixin_445402301 小时前
C++中的命令模式变体
开发语言·c++·算法
季明洵1 小时前
C语言实现顺序表
数据结构·算法·c·顺序表
Hgfdsaqwr1 小时前
实时控制系统优化
开发语言·c++·算法
2301_821369611 小时前
嵌入式实时C++编程
开发语言·c++·算法
sjjhd6521 小时前
多核并行计算优化
开发语言·c++·算法