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;
    }
};
相关推荐
Q741_147几秒前
C++ 分治 快速选择算法 堆排序 TopK问题 力扣 215. 数组中的第K个最大元素 题解 每日一题
c++·算法·leetcode·分治·1024程序员节·topk问题·快速选择算法
文火冰糖的硅基工坊4 分钟前
[人工智能-大模型-57]:模型层技术 - 软件开发的不同层面(如底层系统、中间件、应用层等),算法的类型、设计目标和实现方式存在显著差异。
人工智能·算法·中间件
鱼儿也有烦恼9 分钟前
快速学完 LeetCode top 1~50 [特殊字符]
java·算法·leetcode·1024程序员节
独自破碎E10 分钟前
LeetCode 380: O(1) 时间插入、删除和获取随机元素
java·算法·leetcode
Brookty20 分钟前
【算法】前缀和(二)使用
java·学习·算法·前缀和·动态规划·1024程序员节
不良人龍木木33 分钟前
云图-地基云图
图像处理·算法·计算机视觉·1024程序员节
RTC老炮35 分钟前
webrtc弱网-PccNetworkController类源码分析与算法原理
网络·算法·webrtc
Swift社区41 分钟前
LeetCode 406 - 根据身高重建队列
算法·leetcode·1024程序员节
敲上瘾43 分钟前
背包dp——动态规划
c++·算法·动态规划
京东零售技术1 小时前
大模型时代的广告营销变革与实践
算法