forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1905-count-sub-islands.py
33 lines (29 loc) · 935 Bytes
/
1905-count-sub-islands.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 countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
ROWS, COLS = len(grid1), len(grid1[0])
visit = set()
def dfs(r, c):
if (
r < 0
or c < 0
or r == ROWS
or c == COLS
or grid2[r][c] == 0
or (r, c) in visit
):
return True
visit.add((r, c))
res = True
if grid1[r][c] == 0:
res = False
res = dfs(r - 1, c) and res
res = dfs(r + 1, c) and res
res = dfs(r, c - 1) and res
res = dfs(r, c + 1) and res
return res
count = 0
for r in range(ROWS):
for c in range(COLS):
if grid2[r][c] and (r, c) not in visit and dfs(r, c):
count += 1
return count