-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsol.py
53 lines (47 loc) · 1.47 KB
/
sol.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from typing import List
EMPTY = 0
FRESH = 1
ROTTEN = 2
class Solution:
def is_near_rotten(self, x, y, grid: List[List[int]]) -> bool:
height = len(grid)
width = len(grid[0])
if y > 0:
if grid[y-1][x] == ROTTEN:
return True
if y < height - 1:
if grid[y+1][x] == ROTTEN:
return True
if x > 0:
if grid[y][x-1] == ROTTEN:
return True
if x < width - 1:
if grid[y][x+1] == ROTTEN:
return True
return False
def print(self, grid: List[List[int]]):
for row in grid:
print(row)
print("-----")
def orangesRotting(self, grid: List[List[int]]) -> int:
updates = []
rounds = 0
while True:
for y, row in enumerate(grid):
for x, _ in enumerate(row):
if grid[y][x] == ROTTEN or grid[y][x] == EMPTY:
continue
if self.is_near_rotten(x, y, grid):
updates.append((x, y))
self.print(grid)
if not updates:
break
rounds += 1
for update in updates:
grid[update[1]][update[0]] = ROTTEN
updates = []
for y, row in enumerate(grid):
for x, _ in enumerate(row):
if grid[y][x] == FRESH:
return -1
return rounds