Skip to content

Commit 0c00cde

Browse files
committed
solve 3
1 parent b0d7f1b commit 0c00cde

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

β€Žnumber-of-islands/pmjuu.pyβ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
μ‹œκ°„ λ³΅μž‘λ„: O(m * n)
3+
- 각 셀을 ν•œ λ²ˆμ”© λ°©λ¬Έν•˜λ©°, DFSλ₯Ό 톡해 μ—°κ²°λœ λͺ¨λ“  셀을 ν™•μΈν•˜λ―€λ‘œ grid의 λͺ¨λ“  셀에 λŒ€ν•΄ O(1) μž‘μ—…μ΄ μˆ˜ν–‰λ©λ‹ˆλ‹€.
4+
5+
곡간 λ³΅μž‘λ„: O(m * n)
6+
- μ΅œμ•…μ˜ 경우, DFS의 호좜 μŠ€νƒμ΄ 격자의 λͺ¨λ“  셀에 λŒ€ν•΄ μŒ“μΌ 수 μžˆμŠ΅λ‹ˆλ‹€. 이 경우 μŠ€νƒμ— μ €μž₯λ˜λŠ” μ…€μ˜ κ°œμˆ˜λŠ” μ΅œλŒ€ m * n μž…λ‹ˆλ‹€.
7+
'''
8+
9+
from typing import List
10+
11+
12+
class Solution:
13+
def numIslands(self, grid: List[List[str]]) -> int:
14+
count = 0
15+
m, n = len(grid), len(grid[0])
16+
17+
def exploreIsland(row: int, col: int):
18+
withinBounds = (0 <= row < m) and (0 <= col < n)
19+
if not withinBounds or grid[row][col] != "1":
20+
return
21+
22+
grid[row][col] = "#"
23+
24+
exploreIsland(row + 1, col)
25+
exploreIsland(row - 1, col)
26+
exploreIsland(row, col + 1)
27+
exploreIsland(row, col - 1)
28+
29+
# Iterate through all cells in the grid
30+
for i in range(m):
31+
for j in range(n):
32+
# if a cell is "1", increment count and mark the whole island as "#"
33+
if grid[i][j] == "1":
34+
count += 1
35+
exploreIsland(i, j)
36+
37+
return count

0 commit comments

Comments
Β (0)