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;
    }
};
相关推荐
xiaoye-duck6 分钟前
《算法题讲解指南:递归,搜索与回溯算法--穷举vs深搜vs回溯vs剪枝》--12.全排列,13.子集
c++·算法·回溯
Darkwanderor8 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo9 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣9 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣9 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟11 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot12 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了13 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz13 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法