-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotting_oranges.py
32 lines (27 loc) · 1.02 KB
/
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
from collections import deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
que = deque()
rows = len(grid)
cols = len(grid[0])
visited = [[False for _ in range(cols)] for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
visited[r][c] = True
que.append((r, c, 0))
l = 0
while que:
r, c, l = que.popleft()
for pos in [(1, 0), (-1, 0), (0, -1), (0, 1)]:
newr, newc = r + pos[0], c + pos[1]
if newr < 0 or rows <= newr or newc < 0 or cols <= newc or grid[newr][newc] == 0 or visited[newr][newc]:
continue
grid[newr][newc] = 2
visited[newr][newc] = True
que.append((newr, newc, l + 1))
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
return -1
return l