소프트웨어에 대한 모든 것

LeetCode 풀기 - 200. Number of Islands 본문

알고리즘/LeetCode

LeetCode 풀기 - 200. Number of Islands

앤테바 2022. 2. 23. 19:37
반응형

200. Number of Islands

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

문제)

솔루션1) DFS

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        m,n = len(grid), len(grid[0])
        visited = [[0]*n for i in range(m)]
        
        island_count = 0        
        def recur(row, col):
       		# boundary check
            if not (0 <= row < m): return
            if not (0 <= col < n): return
            
            if grid[row][col] == '0' or visited[row][col] == 1:
                return
            
            visited[row][col] = 1
            
            recur(row-1, col)
            recur(row+1, col)
            recur(row, col-1)
            recur(row, col+1)
        
        for row in range(m):
            for col in range(n):
                if grid[row][col] == '1' and visited[row][col] == 0:
                    island_count += 1
                    recur(row, col)
        
        return island_count

 

 

반응형
Comments