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;
    }
};
相关推荐
x***J34814 分钟前
算法竞赛训练方法
算法
前端小L17 分钟前
图论专题(十六):“依赖”的死结——用拓扑排序攻克「课程表」
数据结构·算法·深度优先·图论·宽度优先
前端小L18 分钟前
图论专题(十三):“边界”的救赎——逆向思维解救「被围绕的区域」
数据结构·算法·深度优先·图论
风筝在晴天搁浅22 分钟前
代码随想录 738.单调递增的数字
数据结构·算法
Miraitowa_cheems33 分钟前
LeetCode算法日记 - Day 108: 01背包
数据结构·算法·leetcode·深度优先·动态规划
九年义务漏网鲨鱼1 小时前
【多模态大模型面经】现代大模型架构(一): 组注意力机制(GQA)和 RMSNorm
人工智能·深度学习·算法·架构·大模型·强化学习
闲人编程1 小时前
CPython与PyPy性能对比:不同解释器的优劣分析
python·算法·编译器·jit·cpython·codecapsule
杜子不疼.1 小时前
【C++】深入解析AVL树:平衡搜索树的核心概念与实现
android·c++·算法
小武~1 小时前
Leetcode 每日一题C 语言版 -- 88 merge sorted array
c语言·算法·leetcode
e***U8201 小时前
算法设计模式
算法·设计模式