Skip to content

Commit 98d18de

Browse files
solves Number of closed islands (#1254) in python
1 parent d7b47d3 commit 98d18de

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

python/number_of_closed_islands.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# https://leetcode.com/problems/number-of-closed-islands/description/
2+
# T: O(m*n)
3+
# S: O(m*n)
4+
5+
class Solution:
6+
def closedIsland(self, grid: List[List[int]]) -> int:
7+
m = len(grid)
8+
n = len(grid[0])
9+
visit = [[False] * n for _ in range(m)]
10+
count = 0
11+
12+
def dfs(x: int, y: int, m: int, n: int, grid: List[List[int]], visit: List[List[bool]]) -> bool:
13+
if x < 0 or x >= m or y < 0 or y >= n:
14+
# (x, y) is a boundary cell.
15+
return False
16+
if grid[x][y] == 1 or visit[x][y]:
17+
# (x, y) is not a valid cell to visit.
18+
return True
19+
visit[x][y] = True
20+
isClosed = True
21+
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
22+
isClosed &= dfs(x + dx, y + dy, m, n, grid, visit)
23+
return isClosed
24+
25+
for i in range(m):
26+
for j in range(n):
27+
if grid[i][j] == 0 and not visit[i][j] and dfs(i, j, m, n, grid, visit):
28+
count += 1
29+
30+
return count

0 commit comments

Comments
 (0)