코딩테스트

Leetcode Q.200 [Medium]: DFS

lukeit 2024. 8. 20. 13:08

 

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

 

Example 1:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1
Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3
 

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0

        def dfs(i,j):
            if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != '1':
                # if the cell is out of the grid boundaries (i < 0 or j < 0) or not land(grid[i][j] != 1),
                # return
                return

            # if land or inside the grid, make as visited by changing from 1 to 0
            grid[i][j] = '0'
            dfs(i+1, j)
            dfs(i-1, j)
            dfs(i, j+1)
            dfs(i, j-1)

        num_islands = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1':
                    num_islands += 1
                    dfs(i,j)
    
        return num_islands

 

Time Complexity: O(r*c)

Mechanism:

 

- Iterate through each cell in the grid, when encountering an unvisited '1', increment the num_islands and trigger DFS to explore and mark all connected land cells belonging to this island.

 

 

배운점: dfs()를 사용해 grid 탐색

 

반응형