Skip to content

Commit 2c79e10

Browse files
committed
feat: [Week 07-3] solve Number of Islands
1 parent 312e412 commit 2c79e10

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Solution:
3+
1) for ๋ฌธ์„ ๋Œ๋ฉด์„œ ์„ฌ(1)์ธ ๊ฒฝ์šฐ result ์— 1์„ ๋”ํ•˜๊ณ  dfs๋ฅผ ๋Œ๋ฆฐ๋‹ค.
4+
2) dfs ๋ฅผ ํ†ตํ•ด ์„ฌ ์ „์ฒด๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ 0์œผ๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค.
5+
3) ์„ฌ์˜ ๊ฐฏ์ˆ˜ result ๋ฅผ return ํ•œ๋‹ค.
6+
7+
์œก์ง€์˜ ๊ฐฏ์ˆ˜ n
8+
Time: O(n) nํšŒ์˜ dfs ํ•จ์ˆ˜ ์‹คํ–‰ ๋  ์ˆ˜ ์žˆ์Œ
9+
Space: O(n) n์˜ ํ˜ธ์ถœ์Šคํƒ์ด ์‚ฌ์šฉ ๋  ์ˆ˜ ์žˆ์Œ
10+
"""
11+
12+
13+
class Solution:
14+
def numIslands(self, grid: List[List[str]]) -> int:
15+
ROWS, COLS = len(grid), len(grid[0])
16+
result = 0
17+
18+
def dfs(i, j):
19+
if i < 0 or i >= ROWS or j < 0 or j >= COLS or grid[i][j] == "0":
20+
return
21+
grid[i][j] = "0"
22+
for dx, dy in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
23+
dfs(i + dx, j + dy)
24+
25+
for i in range(ROWS):
26+
for j in range(COLS):
27+
if grid[i][j] == "1":
28+
dfs(i, j)
29+
result += 1
30+
31+
return result

0 commit comments

Comments
ย (0)