Skip to content

Commit 202b2de

Browse files
committed
number of island solution
1 parent b5b3c4c commit 202b2de

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

number-of-islands/hyeri0903.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def numIslands(self, grid: List[List[str]]) -> int:
3+
'''
4+
m = 세로(열), n = 가로(행)
5+
solution: dfs
6+
'''
7+
m = len(grid)
8+
n = len(grid[0])
9+
visited = [ [0] * n for _ in range(m)]
10+
count = 0
11+
12+
def dfs(i, j):
13+
#범위 벗어나면 return
14+
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == "0":
15+
return
16+
17+
if visited[i][j] == 1:
18+
return
19+
20+
visited[i][j] = 1 #방문표시
21+
22+
dfs(i+1, j)
23+
dfs(i-1, j)
24+
dfs(i, j+1)
25+
dfs(i, j-1)
26+
27+
for i in range(m):
28+
for j in range(n):
29+
if grid[i][j] == "1" and visited[i][j] == 0:
30+
dfs(i,j)
31+
count += 1
32+
return count
33+

0 commit comments

Comments
 (0)