◀ THE GRIND — GRAPHS

Number of Islands

MEDIUM✓ CHIP-TIMEDLC #200 — FULL STATEMENT ↗

The drill: A grid of '1' (land) and '0' (water) cells — count how many separate islands exist, where land only connects up, down, left, or right, never diagonally.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A grid of characters, each either '1' for land or '0' for water, represents a small stretch of coastline. The task is to count how many separate islands sit in that grid, where an island is any group of land cells joined edge to edge.

Two land cells only belong to the same island when connected up, down, left, or right — a diagonal touch never merges two islands into one, no matter how close the corners sit.

The grid is scanned as a whole; nothing needs sorting or ranking, just a count of distinct connected land groups by the time every cell has been looked at.

EX 01
grid = ["1"]
1
SINGLE LAND CELL
EX 02
grid = ["0"]
0
SINGLE WATER CELL
EX 03
grid = ["101"]
2
TWO ISLANDS SEPARATED BY WATER
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every land cell belongs to exactly one island; the question is how many separate blobs of connected land exist. What operation turns 'walk through everything connected to me' into a single check?

HINT 2 THE STRUCTURE

Flood fill: starting from any unvisited land cell, mark every cell reachable through land moves as belonging to the same island, then never look at those cells again.

HINT 3 ONE STEP FROM THE ANSWER

Scan every cell; each time you hit unvisited land, that's a brand-new island — flood-fill outward from it (BFS or DFS) to consume the whole blob before continuing the scan.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE SINK COUNTPATTERN · DFS, SINK IN PLACEgrid = ["110","010","001"]
1
1
0
0
1
0
0
0
1
STEP 1

Scan every cell left to right, top to bottom. Each unvisited '1' starts a brand-new island, then DFS sinks its whole blob to '0'.

STEP 1 / 8 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/number-of-islands.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        rows, cols = len(grid), len(grid[0])

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

        islands = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == '1':
                    islands += 1
                    sink(r, c)
        return islands
TIME O(ROWS·COLS)SPACE O(ROWS·COLS) WORST CASE (CALL STACK)PYTHON · RACE PACE · 20 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED