Skip to content

Commit 04c6c98

Browse files
committed
[7th batch] week 7 - number of islands
1 parent 7c741cb commit 04c6c98

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 7๊ธฐ ํ’€์ด
2+
# ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n * m)
3+
# - grid์˜ ํฌ๊ธฐ n * m ์— ๋”ฐ๋ผ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ •ํ•ด์ง(์ตœ์•…์€ ๋ชจ๋“  grid ์ธ๋ฑ์Šค๋ฅผ ๋‹ค ๋Œ ๋•Œ)
4+
# ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n * m)
5+
# - ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์˜ ์ตœ๋Œ€ ํฌ๊ธฐ๋Š” grid ์ด์ฐจ ๋ฐฐ์—ด์˜ ํฌ๊ธฐ์™€ ๋™์ผ
6+
class Solution:
7+
def numIslands(self, grid: List[List[str]]) -> int:
8+
len_i, len_j = len(grid), len(grid[0])
9+
directions = [(1, 0), (-1, 0), (0, -1), (0 , 1)] # ํƒ์ƒ‰ ๋ฐฉํ–ฅ(์œ„, ์•„๋ž˜, ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ์ˆœ)
10+
11+
res = 0
12+
13+
def dfs(i, j):
14+
grid[i][j] = "0" # ๋ฐฉ๋ฌธ์„ ํ–ˆ์œผ๋ฉด grid์˜ ๊ฐ’์„ "0"์œผ๋กœ ๋ณ€๊ฒฝํ•ด ๋‹ค์Œ ํƒ์ƒ‰ ์‹œ ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๋„๋ก ํ•จ
15+
for dir_i, dir_j in directions:
16+
next_i, next_j = i + dir_i, j + dir_j
17+
18+
# ๋‹ค์Œ ํƒ์ƒ‰ ์ธ๋ฑ์Šค๊ฐ€ ๋ฐฐ์—ด ๋ฒ”์œ„ ๋‚ด์ด๋ฉด์„œ
19+
# grid[next_i][next_j]๊ฐ€ "1"์ด์–ด์•ผ ๊ทธ ๋‹ค์Œ ๋ฐฉ๋ฌธ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.
20+
if (
21+
0 <= next_i < len_i
22+
and 0 <= next_j < len_j
23+
and grid[next_i][next_j] == "1"
24+
):
25+
dfs(next_i, next_j)
26+
27+
for i in range(len_i):
28+
for j in range(len_j):
29+
if grid[i][j] == "0": # grid๊ฐ€ "0"์ผ ๋• ์„ฌ์ด ์•„๋‹ˆ๋ฏ€๋กœ ํƒ์ƒ‰ํ•˜์ง€ ์•Š๋Š”๋‹ค.
30+
continue
31+
dfs(i, j) # ์„ฌ ์ฐพ๊ธฐ
32+
res += 1 # ์„ฌ์„ ๋‹ค ์ฐพ์€ ํ›„์—” res์— 1์„ ์ถ”๊ฐ€ํ•œ๋‹ค.
33+
34+
return res

0 commit comments

Comments
ย (0)