150强访谈简单

腐烂的橙子

“Rotting Oranges”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个 m x n 网格,其中每个单元格可以具有以下三个值之一:

- 0 代表空单元格,

- 1 代表新鲜橙子,或

- 2 代表烂橙子。

每分钟,任何与腐烂橙子在 4 方向上相邻的新鲜橙子就会腐烂。

返回直到单元格中没有新鲜橙子为止必须经过的最小分钟数。如果不可能,则返回 -1。

编写一个函数 orangesRotting(grid: List[List[int]]) -> int

约束条件
  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2

示例

Example 1
Input
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output
4
Explanation

Minute 0: rotten at (0,0). Fresh at (0,1), (0,2), (1,0), (1,1), (2,1), (2,2). Minute 1: fresh at (0,1) and (1,0) rot. Minute 2: fresh at (0,2) and (1,1) rot. Minute 3: fresh at (2,1) rot. Minute 4: fresh at (2,2) rot.

Example 2
Input
grid = [[2,1,1],[0,1,1],[1,0,1]]
Output
-1
Explanation

The orange in the bottom-left corner (row 2, column 0) is never adjacent to a rotten orange, so it stays fresh.

Need a Hint?
考虑使用特定于图的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。