Level order
- CH4 queue
Breadth-first on a tree: drain one level's worth of the queue at a time.
Step through it →Breadth-first and depth-first search reach everything connected to a start, and mark each node the moment they find it, so nothing is visited twice.
A cell is marked as it's queued, and the check that queues a neighbor skips seen cells. So a cell reachable from two sides is queued by whichever gets there first, and never again.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Code that also checks the four diagonals joins these five cells into one island. Up, down, left and right keep them apart.
Breadth-first on a tree: drain one level's worth of the queue at a time.
Step through it →Depth-first on a tree: each node returns one more than its deeper subtree.
Step through it →Visit every node once and swap its two children.
Step through it →Breadth-first with a map: make each node's clone the moment it's first seen.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
from collections import dequedef num_islands(grid): rows, cols = len(grid), len(grid[0]) seen = set() islands = 0 for r in range(rows): for c in range(cols): if grid[r][c] != "1" or (r, c) in seen: continue islands += 1 seen.add((r, c)) queue = deque([(r, c)]) while queue: row, col = queue.popleft() for nr, nc in ((row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)): if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1" and (nr, nc) not in seen: seen.add((nr, nc)) queue.append((nr, nc)) return islands