408算法题leetcode--第40天

994. 腐烂的橘子

题目地址994. 腐烂的橘子 - 力扣(LeetCode)

题解思路:bfs

时间复杂度:O(mn)

空间复杂度:O(mn)

代码:

cpp 复制代码
class Solution {
public:
    int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};

    int orangesRotting(vector<vector<int>>& grid) {
        // bfs
        int m = grid.size(), n = grid[0].size();
        int fresh = 0;
        queue<pair<int, int>>q;  // 存储栏橘子的位置
        // 第0分钟
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    fresh++;
                } else if (grid[i][j] == 2){
                    q.push({i, j});
                }
            }
        }
        int ret = 0;
        while(!q.empty()){
            int size = q.size();
            bool flag = false;
            for(int i = 0; i < size; i++){
                auto [x, y] = q.front();
                q.pop();
                for(int i = 0; i < 4; i++){
                    int next_x = x + dir[i][0], next_y = y + dir[i][1];
                    if(next_x < 0 || next_x >= m || next_y < 0 || next_y >= n){
                        continue;
                    }
                    if(grid[next_x][next_y] == 1){
                        grid[next_x][next_y] = 2;
                        q.push({next_x, next_y});
                        fresh--;
                        flag = true;
                    }
                }
            }
            if(flag){
                ret++;
            }
        }
        return fresh ? -1 : ret;
    }
};
相关推荐
骑自行车的码农11 分钟前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了34 分钟前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 小时前
322:零钱兑换(三种方法)
算法
NAGNIP19 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队20 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法