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;
    }
};
相关推荐
AI服务老曹4 分钟前
车牌识别算法接入AI视频分析平台的流程和误报优化
人工智能·算法·音视频
神威难绷泪21 分钟前
Linux应用软件编程:线程分离属性 互斥机制 同步机制 死锁
linux·开发语言·算法·线程
小星星闪亮登场38 分钟前
图论--最小生成树(内含二分图)
数据结构·算法·图论·迭代加深·图搜索算法
ZC跨境爬虫1 小时前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
吞下星星的少年·-·1 小时前
The 2025 ICPC Asia East Continent Online Contest (I) A题(模拟+贪心)
算法·贪心·模拟
小程序设计1 小时前
【机械设计】磁粉检测机器人的设计与验证
算法·机器人
Navigator_Z2 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
吃好睡好便好2 小时前
判断函数的使用
学习·算法·matlab·生活·判断函数
2601_956121972 小时前
线性DP(入门)
c++·算法·动态规划
唐维康2 小时前
2026年昆工891考研真题应用题分值分布与重点题型解析
考研