Algorithm/Python

[LeetCode] 200. Number of Islands

🥭맹2 2021. 6. 7. 01:46

1. 문제

https://leetcode.com/problems/number-of-islands/

 

Number of Islands - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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. 마치며

마치며~!