Tensorum
LeetCode 200 · Graph Fundamentals / BFS

Number of Islands

LeetCode 200 · Medium · solution, intuition & step-by-step walkthrough

Count DFS launches from unvisited land.

MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix
256 msruntime · beats 39%
31.3 MBmemory · beats 7%
1approach
14accepted runs · last 15 Sept 2026

This is how I solved Number of Islands (LeetCode 200), a medium problem from the Graph Fundamentals / BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.

How I solved it

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

Loading the step-through…

Number of Islands — FAQ

What is the intuition behind Number of Islands?

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.

How do you solve 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.

What is the time and space complexity of Number of Islands?

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

What are common mistakes in Number of Islands?

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