Sign inEnroll free
DSA Visualizer · 25 visualizationsNumber of Islands
MediumGraphs

Number of Islands

Given an m×n binary grid representing a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. Use DFS: when you find land, flood-fill it to '0' to mark as visited, then increment the island counter.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(m×n) · space O(m×n)
def numIslands(grid: list[list[str]]) -> int:
    if not grid: return 0
    islands = 0

    def dfs(r, c):
        if not (0 <= r < len(grid) and 0 <= c < len(grid[0])):
            return
        if grid[r][c] != '1': return
        grid[r][c] = '0'  # mark visited
        for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
            dfs(r + dr, c + dc)

    for r in range(len(grid)):
        for c in range(len(grid[0])):
            if grid[r][c] == '1':
                dfs(r, c)
                islands += 1
    return islands
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough