Skip to content

Commit 6d50b3d

Browse files
Create 1254. Number of Closed Islands
1 parent 491c898 commit 6d50b3d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

1254. Number of Closed Islands

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def closedIsland(self, grid: List[List[int]]) -> int:
3+
4+
def dfs(i,j, visited):
5+
if (i,j) in visited:
6+
return
7+
if not self.isvalidland and (i == 0 or j == 0 or i == m-1 or j == n-1):
8+
self.isvalidland = True
9+
visited.add((i,j))
10+
11+
for x,y in directions:
12+
if 0 <= i+x < m and 0 <= j+y < n and grid[i+x][j+y] == 0:
13+
dfs( i+x, j+y, visited )
14+
15+
16+
if not grid:
17+
return 0
18+
m = len(grid)
19+
n = len(grid[0])
20+
count = 0
21+
visited = set()
22+
directions = [(0,1),(1,0),(0,-1),(-1,0)]
23+
for i in range(m):
24+
for j in range(n):
25+
self.isvalidland = False
26+
if (i,j) not in visited and grid[i][j] == 0:
27+
dfs(i,j,visited)
28+
count += 1 if(not self.isvalidland) else 0
29+
return count
30+
31+

0 commit comments

Comments
 (0)