Skip to contentKEEP THE CRAFTTHE SANCTUARY

Island Traversal

Treat land cells as an implicit four-neighbor graph. Launch one traversal from each unseen land cell, distinguish discovery from processing, and count connected components without changing the grid.

1 practice exercise8 interview problems

Recognize it when A grid asks for the number or size of connected land regions.

Checking your account…

Island Traversal Code Labs

Turn Movement Rules into Edges

A rectangular grid is a graph without an adjacency list. A land cell is a vertex, and allowed coordinate offsets define its edges. These Labs use 1 for land and four orthogonal neighbors. Diagonal contact therefore does not join two islands, even if they look connected in a picture.

Observe One Component Before Counting Many

island_trace receives a valid starting coordinate and records processed cells in DFS order. It creates neighbors as up, right, down, left and pushes them in reverse so the stack pops the first preferred neighbor first. Bounds are checked before indexing; otherwise a negative row can wrap to Python’s last row instead of describing a valid move.

Trace One Island Frontier

Reference
def island_trace(grid,row,col):
    if not grid or grid[row][col]!=1: return []
    seen=set(); trace=[]; stack=[(row,col)]
    while stack:
        r,c=stack.pop()
        if (r,c) in seen: continue
        seen.add((r,c)); trace.append([r,c])
        neighbors=[(r-1,c),(r,c+1),(r+1,c),(r,c-1)]
        for nr,nc in reversed(neighbors):
            if 0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1 and (nr,nc) not in seen: stack.append((nr,nc))
    return trace
Practice

Implement island_trace(grid,row,col). grid is rectangular and 1 is land. For nonempty grid, (row,col) is a valid cell coordinate. Return visited [row,col] cells in DFS order using up,right,down,left neighbors; empty grid or a water start returns [].

Public tests

  • Visit orthogonal land once

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace One Island Frontier

def island_trace(grid,row,col):
    if not grid or grid[row][col]!=1: return []
    seen=set(); trace=[]; stack=[(row,col)]
    while stack:
        r,c=stack.pop()
        if (r,c) in seen: continue
        seen.add((r,c)); trace.append([r,c])
        neighbors=[(r-1,c),(r,c+1),(r+1,c),(r,c-1)]
        for nr,nc in reversed(neighbors):
            if 0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1 and (nr,nc) not in seen: stack.append((nr,nc))
    return trace

Watch the Stack Prefer Right before Down

Predict island_trace([[1,1],[1,1]],0,0). This fully connected square also exposes a duplicate pending coordinate that the pop-time seen check discards.

Step Executed statement State Why
1 r,c=stack.pop(); seen.add((r,c)); trace.append([r,c]) seen={(0,0)}; trace=[[0,0]] The starting land cell is processed once.
2 if 0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1 and (nr,nc) not in seen: stack.append((nr,nc)) stack=[(1,0),(0,1)] Reversed pushes put right on top of down for the next pop.
3 r,c=stack.pop(); seen.add((r,c)); trace.append([r,c]) trace=[[0,0],[0,1]]; stack=[(1,0)] Right is processed and can discover the lower-right land cell.
4 stack.append((nr,nc)) after processing (1,1), stack=[(1,0),(1,0)] The lower-left cell is pending but not yet seen, so another route pushes it again.
5 seen.add((r,c)); trace.append([r,c]) trace=[[0,0],[0,1],[1,1],[1,0]] The first pop of lower-left contributes exactly one output coordinate.
6 if (r,c) in seen: continue stack=[]; trace unchanged The remaining duplicate is skipped, preserving unique processing.
Print Output
print(island_trace([[1,1],[1,1]],0,0)) [[0, 0], [0, 1], [1, 1], [1, 0]]

This trace marks seen when a cell is popped, then skips later copies of that cell. Two paths may briefly put the same cell on the stack. The skip is what keeps output unique; claiming that every pending entry is unique would misdescribe this Lab.

Count Components with Discovery Marking

The counting Lab uses the stricter schedule-once policy: mark a coordinate before pushing it. An outer scan starts only at unseen land and increments count once. That traversal reaches all land connected to its start, so later cells in the same component cannot launch another count.

Count Grid Components

Reference
def count_islands(grid):
    if not grid: return 0
    seen=set(); count=0
    for row in range(len(grid)):
        for col in range(len(grid[0])):
            if grid[row][col]!=1 or (row,col) in seen: continue
            count+=1; seen.add((row,col)); stack=[(row,col)]
            while stack:
                r,c=stack.pop()
                for nr,nc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1)):
                    if 0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1 and (nr,nc) not in seen:
                        seen.add((nr,nc)); stack.append((nr,nc))
    return count
Practice

Implement count_islands(grid). grid is rectangular and 1 is land. Return the number of orthogonally connected groups of 1 without mutating grid; empty input returns 0.

Public tests

  • Launch once per unseen component

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Count Grid Components

def count_islands(grid):
    if not grid: return 0
    seen=set(); count=0
    for row in range(len(grid)):
        for col in range(len(grid[0])):
            if grid[row][col]!=1 or (row,col) in seen: continue
            count+=1; seen.add((row,col)); stack=[(row,col)]
            while stack:
                r,c=stack.pop()
                for nr,nc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1)):
                    if 0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1 and (nr,nc) not in seen:
                        seen.add((nr,nc)); stack.append((nr,nc))
    return count

The grid is preserved and a set stores visited coordinates. Empty input returns zero components. The rectangular shape is part of the contract because neighbor checks use the first row’s width; a ragged grid needs a different validity check.

Choose the Traversal in an Interview

DFS and BFS both find static components in O(R*C) time because each cell has bounded degree. A list with append and pop is a natural DFS stack; a deque is the BFS queue choice. BFS is necessary when layer distance matters, while an explicit stack avoids recursive depth failures on a long thin island. Use disjoint set for incremental activation rather than rerunning static component scans after each change.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Grid traversal (islands)

Check bounds, check seen, mark, then go four ways.

A 2D grid where cells connect up, down, left and right, and you count or measure connected regions.

Trigger words

  • island
  • flood fill
  • connected cells
  • surrounded regions
  • max area
  • 4-directionally adjacent
from collections import deque

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])
    visited = set()
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != '1' or (r, c) in visited:
                continue
            islands += 1                          # new land: one more island
            visited.add((r, c))                   # mark as soon as you add it
            queue = deque([(r, c)])
            while queue:
                row, col = queue.popleft()
                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nr, nc = row + dr, col + dc
                    if not (0 <= nr < rows and 0 <= nc < cols):
                        continue                  # off the grid
                    if grid[nr][nc] == '1' and (nr, nc) not in visited:
                        visited.add((nr, nc))
                        queue.append((nr, nc))
    return islands

Spot it when

  • 'Number of islands', 'max area', 'surrounded regions'.
  • Flood fill.

Remember

  • Mark a cell visited when you add it to the queue, not when you pop it, so it is never added twice.
  • A visited set leaves the input untouched; overwriting '1' with '0' saves memory, but ask the interviewer first.
  • BFS avoids Python's recursion limit on large grids; a recursive DFS is fine for small grids.

How problems bend it

  • Largest island: Count the cells you pop for each island and keep the maximum.
  • Cells connected to the border: Start the search from every border cell first, then look at what was never reached.
  • Recursive DFS instead of a queue: dfs(r, c): return if out of bounds, not land, or seen; mark it; call dfs on the four neighbours.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Enumerate a component or count all componentsO(R*C)O(R*C)A rectangular grid has at most four neighbor edges per cell; the scan and traversals are linear in its cell count.

Space

O(R*C) for visited coordinates and the frontier; the component trace adds O(R*C) output.

Assumptions

  • island_trace may enqueue duplicate pending cells because it marks on pop; each cell has bounded degree and repeated pops are skipped.
  • Expected O(1) set membership for coordinate tuples supports the traversal bound; adversarial hash behavior is not the intended grid model.
  • The Labs use an explicit list stack and avoid recursive Python call-depth limits.

Invariants Worth Saying Aloud

  1. Every processed cell is orthogonally reachable from the traversal's start.
  2. count_islands marks before pushing, so each land cell is scheduled once.
  3. island_trace marks on pop and skips seen entries; duplicate pending entries never become duplicate output cells.

When To Use Or Avoid Island Traversal

Use It When

  • A static rectangular grid defines land as 1 and connectivity through four orthogonal neighbors.
  • DFS or BFS can enumerate one component while a grid scan finds undiscovered components.

Choose Another Tool When

  • The task asks for shortest unweighted distance; BFS layering adds information that DFS does not.
  • Land activates over time with repeated connectivity queries; disjoint set may avoid rescanning the grid.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Joining diagonal contact as one island

A diagonal offset adds an edge that the four-neighbor component contract does not contain.

Prevent it: List only the movement offsets allowed by the problem.

Avoid

neighbors=[(r+dr,c+dc) for dr,dc in ((1,0),(-1,0),(0,1),(0,-1),(1,1))]

Use instead

neighbors=[(r+dr,c+dc) for dr,dc in ((1,0),(-1,0),(0,1),(0,-1))]

Letting a negative neighbor wrap to the tail

Python accepts row -1, so reading before checking bounds can treat the bottom cell as an upward neighbor of row zero.

Prevent it: Check both coordinate bounds before accessing a candidate cell.

Avoid

is_land=grid[nr][nc]==1

Use instead

is_land=0<=nr<len(grid) and 0<=nc<len(grid[0]) and grid[nr][nc]==1

Scheduling duplicates without a later skip

If two parents schedule one unseen coordinate and processing counts every entry, the region size is inflated.

Prevent it: Mark before pushing as in count_islands, or retain the trace Lab's seen-on-pop skip.

Avoid

for _ in range(2):
    if cell not in seen:
        stack.append(cell)

Use instead

for _ in range(2):
    if cell not in seen:
        seen.add(cell)
        stack.append(cell)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.