Skip to content

Commit 579e493

Browse files
author
Jinbeom
committed
Number of Islands Solution
1 parent 9a4fe5e commit 579e493

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

number-of-islands/kayden.py

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

0 commit comments

Comments
 (0)