1. 문제
https://leetcode.com/problems/number-of-islands/
2. 접근 방법
기본 dfs 문제입니다.
이번에는 중첩함수를 사용해봤스빈다.
1. 육지인지 확인하는 함수 : is_land
2. dfs함수 : dfs
3. 코드
python
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def is_land(x, y):
if 0 <= x < len(grid[0]) and 0 <= y < len(grid) and grid[y][x] == '1':
return True
return False
def dfs(x, y):
if not is_land(x, y):
return
grid[y][x] = '0'
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
cnt = 0
for _y in range(len(grid)):
for _x in range(len(grid[0])):
if grid[_y][_x] == '1':
dfs(_x, _y)
cnt += 1
return cnt
4. 마치며
마치며~!
'Algorithm > Python' 카테고리의 다른 글
[백준 16926] 배열 돌리기1, 2 (0) | 2021.06.07 |
---|---|
[LeetCode] 39. Combination Sum (0) | 2021.06.07 |
[LeetCode] 232. Implement Queue using Stacks (0) | 2021.06.06 |
[LeetCode] 225. Implement Stack using Queues (0) | 2021.06.06 |
[LeetCode] 739. Daily Temperatures (0) | 2021.06.06 |