Count Sub Islands LeetCode solution in Python

1
class Solution(object):
2
def countSubIslands(self, grid1, grid2):
3
m = len(grid1)
4
n = len(grid1[0])
5

6
def dfs(i, j):
7
if i < 0 or i >= m or j < 0 or j >= n or grid2[i][j] == 0:
8
return
9
grid2[i][j] = 0
10
dfs(i + 1, j)
11
dfs(i - 1, j)
12
dfs(i, j + 1)
13
dfs(i, j - 1)
14

15
# here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed
16
for i in range(m):
17
for j in range(n):
18
if grid2[i][j] == 1 and grid1[i][j] == 0:
19
dfs(i, j)
20
# now we just need to count the islands left over
21
count = 0
22
for i in range(m):
23
for j in range(n):
24
if grid2[i][j] == 1:
25

26
dfs(i, j)
27
count += 1
28
return count

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0