-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0994-rotting-oranges.py
33 lines (30 loc) · 1.09 KB
/
0994-rotting-oranges.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
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = collections.deque()
fresh = 0
time = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 1:
fresh += 1
if grid[r][c] == 2:
q.append((r, c))
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while fresh > 0 and q:
length = len(q)
for i in range(length):
r, c = q.popleft()
for dr, dc in directions:
row, col = r + dr, c + dc
# if in bounds and nonrotten, make rotten
# and add to q
if (
row in range(len(grid))
and col in range(len(grid[0]))
and grid[row][col] == 1
):
grid[row][col] = 2
q.append((row, col))
fresh -= 1
time += 1
return time if fresh == 0 else -1