博客
关于我
LeetCode 评论区:你管这难度叫简单???
阅读量:695 次
发布时间:2019-03-16

本文共 2241 字,大约阅读时间需要 7 分钟。

解决方案

要解决这个问题,我们需要模拟橘子腐烂传播的过程。使用广度优先搜索(BFS)来逐层扩散腐烂,直到所有新鲜橘子都被腐蚀。每次处理一个腐烂橘子,会检查其四个邻居,将新鲜邻居腐化并加入队列。

方法思路

  • 初始化:遍历网格,记录初始的腐烂橘子位置,并将它们加入队列。统计新鲜橘子的数量count。
  • BFS处理:每分钟处理队列中的所有腐烂橘子。对于每个腐烂橘子,检查其上下左右的邻居。
  • 腐化邻居:如果邻居是新鲜橘子,将其腐化,加入队列,并减少count。
  • 终止条件:如果在BFS结束后,仍有新鲜橘子存在,返回-1。否则,返回处理所需的分钟数。
  • 解决代码

    import java.util.Deque;import java.util.ArrayDeque;public class orangesRotting02 {    public static int orangesRotting(int[][] grid) {        int rows = grid.length;        int cols = grid[0].length;        Deque
    queue = new ArrayDeque<>(); int count = 0; // 初始化队列,记录初始腐烂点,并统计新鲜点数 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 2) { queue.add(new int[]{i, j}); } else if (grid[i][j] == 1) { count++; } } } int res = 0; while (!queue.isEmpty() && count > 0) { res++; int size = queue.size(); for (int i = 0; i < size; i++) { int[] temp = queue.poll(); int r = temp[0], c = temp[1]; // 上 if (r > 0 && grid[r - 1][c] == 1) { grid[r - 1][c] = 2; count--; queue.add(new int[]{r - 1, c}); } // 下 if (r < rows - 1 && grid[r + 1][c] == 1) { grid[r + 1][c] = 2; count--; queue.add(new int[]{r + 1, c}); } // 左 if (c > 0 && grid[r][c - 1] == 1) { grid[r][c - 1] = 2; count--; queue.add(new int[]{r, c - 1}); } // 右 if (c < cols - 1 && grid[r][c + 1] == 1) { grid[r][c + 1] = 2; count--; queue.add(new int[]{r, c + 1}); } } } return count == 0 ? res : -1; }}

    代码解释

  • 初始化部分:遍历网格,记录初始腐烂点,并将它们加入队列。同时统计新鲜橘子的数量count。
  • BFS处理:每次从队列中取出一个橘子,检查其四个邻居。对于每个有效邻居,检查是否是新鲜橘子,将其腐化,并加入队列,同时减少count。
  • 返回结果:当队列为空时,若count为0,返回处理分钟数res;否则,返回-1。
  • 这个方法通过BFS高效地处理了每个橘子的腐蚀过程,确保在最少的分钟内完成任务。如果无法完成任务,如示例中的某些情况,会返回-1。

    转载地址:http://idhqz.baihongyu.com/

    你可能感兴趣的文章
    NLP项目:维基百科文章爬虫和分类【02】 - 语料库转换管道
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    nmap 使用方法详细介绍
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    nmap指纹识别要点以及又快又准之方法
    查看>>
    Nmap渗透测试指南之指纹识别与探测、伺机而动
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>