-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path994.py
36 lines (35 loc) · 1.18 KB
/
994.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# https://neetcode.io/problems/rotting-fruit
# https://leetcode.com/problems/rotting-oranges/description/
from typing import List
from collections import deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
ROW, COL = len(grid), len(grid[0])
unrotted = set()
q = deque()
for r in range(ROW):
for c in range(COL):
if grid[r][c] == 1:
unrotted.add((r, c))
if grid[r][c] == 2:
q.append((r, c))
if not unrotted:
return 0
def spreadRot(q, r, c):
if r < 0 or c < 0 or r >= ROW or c >= COL or grid[r][c] == 0 or grid[r][c] == 2:
return
grid[r][c] = 2
q.append((r, c))
unrotted.remove((r, c))
minutes = -1
while q:
newQ = deque()
while q:
r, c = q.popleft()
spreadRot(newQ, r - 1, c)
spreadRot(newQ, r + 1, c)
spreadRot(newQ, r, c - 1)
spreadRot(newQ, r, c + 1)
q = newQ
minutes += 1
return -1 if unrotted else minutes