Skip to solution
mediumDSA

How do you count the number of islands in a grid?

255 views
01

Understand the problem

Explain grid traversal.

gridbfsdfs
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Scan the grid; on each unvisited land cell, run DFS/BFS to flood-fill all connected land, marking it visited, and increment a counter. Each connected component is one island. O(rows × cols).

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

DFS flood fill
Run Playground
def num_islands(grid):
    if not grid: return 0
    rows, cols = len(grid), len(grid[0])

    def dfs(r, c):
        if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != '1':
            return
        grid[r][c] = '0'                  # mark visited
        dfs(r+1, c); dfs(r-1, c); dfs(r, c+1); dfs(r, c-1)

    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                count += 1
                dfs(r, c)
    return count


# --- demo ---
grid = [
    ["1", "1", "0", "1"],
    ["1", "0", "0", "0"],
    ["0", "0", "1", "1"],
]
print(num_islands(grid))   # 3
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 86 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.

Back to track