File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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
You canβt perform that action at this time.
0 commit comments