Le migliori 150 intervisteFacile

Arance marce

Guida dettagliata e implementazione Python per il problema "Arance marce".

Dichiarazione del problema

Facile

Ti viene fornita una griglia m x n in cui ciascuna cella può avere uno dei tre valori:

- 0 rappresenta una cella vuota,

- 1 che rappresenta un'arancia fresca, o

- 2 che rappresentano un'arancia marcia.

Ogni minuto, qualsiasi arancia fresca adiacente in 4 direzioni a un'arancia marcia diventa marcia.

Restituisce il numero minimo di minuti che devono trascorrere finché nessuna cella avrà un'arancia fresca. Se ciò è impossibile, restituisci -1.

Scrivi una funzione orangesRotting(grid: List[List[int]]) -> int.

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

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Graphs come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.