forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rotting-oranges.py
36 lines (31 loc) · 993 Bytes
/
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
34
35
36
# Time: O(m * n)
# Space: O(m * n)
import collections
class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
count = 0
q = collections.deque()
for r, row in enumerate(grid):
for c, val in enumerate(row):
if val == 2:
q.append((r, c, 0))
elif val == 1:
count += 1
result = 0
while q:
r, c, result = q.popleft()
for d in directions:
nr, nc = r+d[0], c+d[1]
if not (0 <= nr < len(grid) and \
0 <= nc < len(grid[r])):
continue
if grid[nr][nc] == 1:
count -= 1
grid[nr][nc] = 2
q.append((nr, nc, result+1))
return result if count == 0 else -1