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

力扣刷题994. 腐烂的橘子

994. 腐烂的橘子 - 力扣(LeetCode)

使用bfs,先遍历所有的橘子,统计所有的橘子数量,然后把腐烂的橘子放入队列当中,然后进行bfs遍历,套用bfs的模版,但是每一次出队的橘子(腐烂的橘子)需要统计一下数量,用来bfs结束之后比对是否感腐烂完全。每一层广搜遍历需要把时间加一。

bfs结束后,如果出队的橘子小于统计所有的橘子,说明没有腐烂完全,返回-1 ,如果统计的橘子数量为0,返回0,因为没有橘子腐烂,否则返回统计的时间

import java.util.LinkedList;
import java.util.List;

public class Q994 {
    static int[] dx = {0, 0, -1, 1};
    static int[] dy = {-1, 1, 0, 0};
    public static void main(String[] args) {
        int[][] grid = new int[][]{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
        int[][] grid ={{0}};
        int count = 0;//统计总共的橘子,用来判断bfs结束后是否还有橘子
        int time = -1;
        int bad = 0;
        List<int[]> list = new LinkedList<>();

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] != 0) count++;
                if (grid[i][j] == 2) {
                    list.add(new int[]{i, j});
                }
            }
        }
        //开始bfs
        while (!list.isEmpty()) {
            int len = list.size();

            for (int i = 0; i < len; i++) {
                int[] remove = list.remove(0);
                bad++;
                int x = remove[0];
                int y = remove[1];
                for (int j = 0; j < 4; j++) {
                    int xx = x + dx[j];
                    int yy = y + dy[j];
                    if (xx >= 0 && xx < grid.length && yy >= 0 && yy < grid[0].length) {
                        if (grid[xx][yy] == 1) {
                            list.add(new int[]{xx, yy});
                            grid[xx][yy] = 2;
                        }
                    }
                }
            }
            time++;
        }
        
        if(count == 0) System.out.println(0);
        else if(bad<count) System.out.println(-1);
        else System.out.println(time);;

    }


}

http://www.dtcms.com/a/76202.html

相关文章:

  • 比特币牛市还在不在
  • 「Wi-Fi学习」节能模式
  • Java常用类
  • Android第四次面试总结(基础算法篇)
  • LeetCode-274.H 指数
  • C#进阶(多线程相关)
  • SMT贴片机销售实战技巧解析
  • Python高级:GIL、C扩展与分布式系统深度解析
  • 汽车机械钥匙升级一键启动的优点
  • CentOS下安装ElasticSearch(日志分析)
  • 项目实战:基于瑞萨RA6M5构建多节点OTA升级-创建系统最小框架<三>
  • 【SpringMVC】深入解析基于Spring MVC与AJAX的用户登录全流程——参数校验、Session管理、前后端交互与安全实践
  • CXSMILES介绍
  • 【Linux】浅谈环境变量和进程地址空间
  • APP测试
  • c++初阶易错题(选择)
  • Linux: qemu-user-static 是如何工作的?
  • 初探自定义注意力机制:DAttention的设计与实现
  • 力扣128. 最长连续序列 || 452. 用最少数量的箭引爆气球
  • 如何打造安全稳定的亚马逊采购测评自养号下单系统?
  • 【微知】ip命令如何查看路由表?如何查看IPv6的路由表?(ip r s、ip -6 r s)
  • 【Netty】SimpleChannelInboundHandler如何根据数据类型处理消息
  • 区块链 智能合约安全 | 整型溢出漏洞
  • 对于memset(b, 1, sizeof b)赋值为16843009情况
  • Ansys 2024 R1 安装出现错误码-8544解决方法
  • SPACE_GAME
  • Qt-搭建开发环境
  • 【新能源汽车“心脏”赋能:三电系统研发、测试与应用匹配的恒压恒流源技术秘籍】
  • TF中 Arg 节点
  • 【canvas】一键自动布局:如何让流程图节点自动找到最佳位置