Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 8. 29. 23:45

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

DFS 기초 중의 기초 문제
나는 60% 정도 풀고 생각이 잘 안나서 솔루션 봄.
다음에는 80% 풀어봐야지!

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        m, n = len(grid), len(grid[0])
        cnt = 0
        
        def dfs(a, b, grid):
            if a < 0 or b < 0 or a >= m or b >= n or grid[a][b] != '1':
                return
            grid[a][b] = '#'
            dfs(a+1, b, grid)
            dfs(a-1, b, grid)
            dfs(a, b+1, grid)
            dfs(a, b-1, grid)
            
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    dfs(i, j, grid)
                    cnt += 1
        return cnt
반응형