Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit dbb5ce9

Browse files
author
sejineer
committedMay 18, 2025·
number-of-islands solution
1 parent 23cd8fc commit dbb5ce9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
 

‎number-of-islands/sejineer.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
시간 복잡도: O(m * n)
3+
공간 복잡도: O(m * n)
4+
"""
5+
from collections import deque
6+
7+
class Solution:
8+
def numIslands(self, grid: List[List[str]]) -> int:
9+
m, n = len(grid), len(grid[0])
10+
vis = [[False] * n for _ in range(m)]
11+
12+
dx = [1, -1, 0, 0]
13+
dy = [0, 0, 1, -1]
14+
15+
result = 0
16+
for i in range(m):
17+
for j in range(n):
18+
if grid[i][j] == '1' and not vis[i][j]:
19+
queue = deque()
20+
queue.append((j, i))
21+
vis[i][j] = True
22+
while queue:
23+
cur = queue.popleft()
24+
for nxt in range(4):
25+
nx = cur[0] + dx[nxt]
26+
ny = cur[1] + dy[nxt]
27+
if not 0 <= nx < n or not 0 <= ny < m:
28+
continue
29+
if vis[ny][nx] or grid[ny][nx] != '1':
30+
continue
31+
queue.append((nx, ny))
32+
vis[ny][nx] = True
33+
result += 1
34+
35+
return result

0 commit comments

Comments
 (0)
Please sign in to comment.