File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def numIslands (self , grid : List [List [str ]]) -> int :
3+
4+ # DFS (์๊ฐ๋ณต์ก๋ O(m*n), ๊ณต๊ฐ๋ณต์ก๋ O(m*n))
5+ answer = 0 # ์ฌ์ ์
6+ m = len (grid )
7+ n = len (grid [0 ])
8+
9+ # ํ๋์ ์ฌ ์ฒ๋ฆฌ(์ฐ๊ฒฐ๋ ๋
๋ชจ๋ ๋ฐฉ๋ฌธ)
10+ def dfs (x ,y ):
11+ # ๋ฒ์๋ฅผ ๋ฒ์ด๋๊ฑฐ๋, ์ด๋ฏธ ๋ฐฉ๋ฌธํ๊ฑฐ๋, ๋
์ด ์๋๋ฉด ์ข
๋ฃ
12+ if x < 0 or y < 0 or x >= m or y >= n or grid [x ][y ] != "1" :
13+ return
14+
15+ # ํ์ฌ ๋
๋ฐฉ๋ฌธ์ฒ๋ฆฌ
16+ grid [x ][y ] = "*"
17+
18+ # ์ํ์ข์ฐ ํ์
19+ dfs (x + 1 , y )
20+ dfs (x - 1 , y )
21+ dfs (x , y + 1 )
22+ dfs (x , y - 1 )
23+
24+ for i in range (m ):
25+ for j in range (n ):
26+ # ๋
๋ฐ๊ฒฌ์ dfs๋ก ์ฐ๊ฒฐ๋์ด ์๋ ๋ชจ๋ ๋
๋ฐฉ๋ฌธํ๊ณ ์ฌ+1 ์ฒ๋ฆฌ
27+ if grid [i ][j ] == "1" :
28+ dfs (i ,j )
29+ answer += 1
30+
31+ return answer
You canโt perform that action at this time.
0 commit comments