-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC0437.py
43 lines (38 loc) · 1.32 KB
/
LC0437.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
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
def _count_islands():
visited = set()
count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1 and (i, j) not in visited:
_explore_island(i, j, visited)
count += 1
return count
def _explore_island(i, j, visited):
if (
i < 0
or i >= rows
or j < 0
or j >= cols
or grid[i][j] == 0
or (i, j) in visited
):
return
visited.add((i, j))
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
_explore_island(i + di, j + dj, visited)
# Check if already disconnected
if _count_islands() != 1:
return 0
# Check if can be disconnected in 1 day
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
grid[i][j] = 0
if _count_islands() != 1:
return 1
grid[i][j] = 1
# If can't be disconnected in 0 or 1 day, return 2
return 2