Tech for good

[Leetcode/DFS, BFS, Graph, Matrix] 200. Number of Islands 본문

IT/Computer Science

[Leetcode/DFS, BFS, Graph, Matrix] 200. Number of Islands

Diana Kang 2025. 8. 9. 07:00

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        n_rows, n_cols = len(grid), len(grid[0])

        res = 0
        visited = set()

        def dfs(r, c):
            visited.add((r,c))

            neighbors = [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]

            # check if visited or not
            for n_r, n_c in neighbors:
                if n_r in range(n_rows) and n_c in range(n_cols):
                    if grid[n_r][n_c] == "1" and (n_r, n_c) not in visited:
                        dfs(n_r, n_c)
        
        # check grid one by one
        for r in range(n_rows):
            for c in range(n_cols):
                # If the cell is land and not visited, it's a new island
                if grid[r][c] == "1" and (r,c) not in visited:
                    # # Explore the entire island using DFS
                    dfs(r,c)
                    # # Increase the island count
                    res += 1

        return res