994. Rotting Oranges
package LeetCode_994 import java.util.* /** * 994. Rotting Oranges * https://leetcode.com/problems/rotting-oranges/ * * In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. * */ class Solution { /* * solution: bfs, check every position in grid * Time complexity:O(mn), Space complexity:O(mn) * */ fun orangesRotting(grid: Array<IntArray>): Int { if (grid == null || grid.isEmpty()) { return 0 } val m = grid.size val n = grid[0].size val directions = intArrayOf(0, 1, 0, -1, 0) var freshCount = 0 val queue = LinkedList<Pair<Int, Int>>() var time = 0 //save all rotten orange and count fresh orange for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] == 2) { queue.offer(Pair(i, j)) } else if (grid[i][j] == 1) { freshCount++ } } } //use freshCount>0 to avoid do one more useless loop while (queue.isNotEmpty() && freshCount > 0) { //increase time at each level time++ //the size of rotten orange of current level val size = queue.size for (i in 0 until size) { //get the rotten orange val cur = queue.pop() //checking 4 directions of cur for (d in 0 until 4) { val x = cur.first + directions[d] val y = cur.second + directions[d + 1] if (x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 0 || grid[x][y] == 2) { continue } //set new x,y to rotten grid[x][y] = 2 //reduce freshCount freshCount-- //put into queue for next level queue.offer(Pair(x, y)) } } } return if (freshCount == 0) time else -1 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)