当前位置: 首页 > article >正文

408算法题leetcode--第40天

994. 腐烂的橘子

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

题解思路:bfs

时间复杂度:O(mn)

空间复杂度:O(mn)

代码:

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;
    }
};

http://www.kler.cn/news/366407.html

相关文章:

  • 没错,Go 语言的函数参数没有引用传递方式
  • AndroidStudio新建Native项目报错[CXX1429]
  • 聚类分析算法——DBSCAN(密度聚类)算法详解
  • C++面向对象编程学习
  • Redis Search系列 - 第六讲 基准测试 - Redis Search VS. MongoDB VS. ElasticSearch
  • ResNet-RS 乳腺癌识别
  • MemoRAG:重新定义长期记忆的AI问答模型
  • 如何测手机到路由器的内网带宽【使用iperf3】
  • 【Android常见开发模式】
  • 尚硅谷-react教程-求和案例-数据共享(下篇)-完成数据共享-笔记
  • 神经种群动态优化算法(NPDOA)-2024年9年SCI一区新算法-公式原理详解 Matlab代码免费获取
  • LeetCode 热题100之哈希
  • Android Activity 自定义方法 不混淆,可以使用@Keep注解
  • go 内存分配管理
  • 安全见闻6-7
  • NumPy学习Day18
  • RHCSA基础命令整理1
  • 将jinjia2后端传到前端的字典数据转化为json
  • 【实验六】基于前馈神经网络的二类任务
  • 梦熊十三联测 A题 加减乘除
  • JS无限执行隔行变色
  • 这是一篇vue3 的详细教程
  • 机器学习5
  • Flume的安装及使用
  • 中国人寿财险青岛市分公司践行绿色金融,助力可持续发展
  • 【mysql】转义字符反斜杠,正则表达式