Skip to content

Commit e366da3

Browse files
authored
Create count-sub-islands.py
1 parent 15cedb5 commit e366da3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Python/count-sub-islands.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Time: O(m * n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def countSubIslands(self, grid1, grid2):
6+
"""
7+
:type grid1: List[List[int]]
8+
:type grid2: List[List[int]]
9+
:rtype: int
10+
"""
11+
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
12+
def dfs(grid1, grid2, i, j):
13+
if not (0 <= i < len(grid2) and
14+
0 <= j < len(grid2[0]) and
15+
grid2[i][j] == 1):
16+
return 1
17+
grid2[i][j] = 0
18+
result = grid1[i][j]
19+
for di, dj in directions:
20+
result &= dfs(grid1, grid2, i+di, j+dj)
21+
return result
22+
23+
return sum(dfs(grid1, grid2, i, j) for i in xrange(len(grid2)) for j in xrange(len(grid2[0])) if grid2[i][j])

0 commit comments

Comments
 (0)