Skip to content

Commit 3113880

Browse files
committed
number-of-islands
1 parent b78caa7 commit 3113880

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

number-of-islands/i-mprovising.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
"""
3+
Time, Space comlexity O(n*m)
4+
5+
connected components
6+
dfs, bfs
7+
"""
8+
def numIslands(self, grid: List[List[str]]) -> int:
9+
n, m = len(grid), len(grid[0])
10+
visited = [[False for _ in range(m)] for _ in range(n)] # visited 대신 grid를 0으로 표시할수도 있다
11+
islands = 0
12+
13+
def dfs(x, y):
14+
stack = [(x, y)]
15+
while stack:
16+
x, y = stack.pop()
17+
dx = [-1, 1, 0, 0]
18+
dy = [0, 0, -1, 1]
19+
for k in range(4):
20+
nx, ny = x + dx[k], y + dy[k]
21+
if 0<=nx<=n-1 and 0<=ny<=m-1:
22+
if not visited[nx][ny] and grid[nx][ny] == "1":
23+
visited[nx][ny] = True
24+
stack.append((nx, ny))
25+
26+
for i in range(n):
27+
for j in range(m):
28+
if not visited[i][j] and grid[i][j] == "1":
29+
dfs(i, j)
30+
islands += 1
31+
32+
return islands

0 commit comments

Comments
 (0)