Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 200 · Graph Fundamentals / BFS

Number of Islands

LeetCode 200 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Count DFS launches from unvisited land.

ಮಧ್ಯಮArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Number of Islands (LeetCode 200) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Graph Fundamentals / BFS ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Each island is a connected group of '1' cells. Scan the grid; every unvisited land cell starts a new island, and a DFS marks all of its connected land as visited.

Approach

  1. 1

    Visited set.

  2. 2

    For each '1' not yet visited: DFS, count++.

  3. 3

    DFS marks the cell and recurses into land neighbours.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Grid DFSPythonO(m·n) time
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        """
        Simple DFS
        """
        visited = set()
        components = 0
        m = len(grid)
        n = len(grid[0])
        def dfs(row,col):
            visited.add((row,col))
            di = [0,+1,0,-1]
            dj = [+1,0,-1,0]
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and (nrow,ncol) not in visited and grid[nrow][ncol]=="1":
                    dfs(nrow,ncol)
        for row in range(m):
            for col in range(n):
                if grid[row][col]=="1" and (row,col) not in visited:
                    dfs(row,col)
                    components+=1
        return components

ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Number of Islands — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Number of Islands ಹಿಂದಿನ intuition ಏನು?

Each island is a connected group of '1' cells. Scan the grid; every unvisited land cell starts a new island, and a DFS marks all of its connected land as visited.

Number of Islands (LeetCode 200) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Visited set. 2. For each '1' not yet visited: DFS, count++. 3. DFS marks the cell and recurses into land neighbours.

Number of Islands ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(m · n). Space: O(m · n). (Accepted approach: Grid DFS.)

Number of Islands ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Deep recursion on huge grids — BFS or marking the grid in place avoids it.