Translating Grids and Dependencies into Graph Primitives
Many candidates freeze on graph questions only when the prompt avoids the word "graph." A 2D warehouse map of fresh and rotting fruit, a word-ladder transformation, or a build-system task list are all graphs in disguise.
Before picking an algorithm, I separate two jobs: minimum hop distance vs. reachability and dependency ordering. As the CP-Algorithms BFS guide proves, a single-queue breadth-first wave reaches every node by its minimum unweighted edge count. Directed dependency graphs, by contrast, ask for cycle checks or linear execution order via topological sorting.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Core Intuitions and State Invariants
1. Mark visited on enqueue in BFS, never on pop
Whether traversing an explicit adjacency list or an implicit 4-neighbor grid, the single deadliest BFS bug is waiting until q.popleft() to mark a cell visited. When two level- neighbors both inspect the same unvisited level- cell, both push it onto the queue, compounding duplicate work layer by layer.
Mark a node visited (or mutate the grid cell from 1 to 2) at the exact moment you append it to the deque. For multi-source spreading waves, push every initial source at time 0 before starting the loop so all rings expand in lockstep. When an interviewer asks you to reconstruct the shortest path rather than only return its length (such as in Word Ladder II or maze routing), store a parent dictionary mapping neighbor -> curr when enqueuing and walk backward from target to start after discovery.
Notice how grid islands (Number of Islands) and multi-source wave expansion share the exact same boundary helper 0 <= nr < rows and 0 <= nc < cols: DFS flood-fill collects connected landmass size or counts components, while BFS measures minimum steps across obstacles.
2. Three-color DFS vs. Kahn's topological sort
For undirected graphs, a simple boolean visited array plus tracking parent catches cycles whenever an edge hits an already visited non-parent vertex. In a directed graph, boolean visited breaks on a harmless diamond DAG (0 -> 1 -> 2 and 0 -> 2): reaching 2 a second time does not imply a cycle.
As explained in CP-Algorithms cycle detection, directed DFS uses three states: 0 (unvisited), 1 (currently on active recursion stack), and 2 (finished). Only an edge into state 1 proves a back-edge cycle. Remember that reversing post-order DFS exit times also produces a topological sort, which makes it natural when you already run recursive DFS.
For interview implementation, I usually prefer Kahn's iterative algorithm: compute indegree[v] for all vertices, enqueue every 0-indegree node, pop one node at a time into order, and decrement each neighbor's indegree. Every edge relaxes once, and if len(order) < n, a cycle blocked the remaining vertices. Better yet, if a prompt asks for the lexicographically smallest valid ordering across multiple choices, swapping deque for a heapq min-heap in Kahn's loop solves the constraint in with a two-line edit.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Working Python Code
Here are tested Python implementations covering multi-source grid BFS (minutes_to_rot), Kahn's topological sort (topo_order), and 3-color directed cycle check (has_directed_cycle).
from collections import deque
def minutes_to_rot(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
work = [row[:] for row in grid]
q: deque[tuple[int, int]] = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if work[r][c] == 2:
q.append((r, c))
elif work[r][c] == 1:
fresh += 1
minutes = 0
while q and fresh > 0:
minutes += 1
for _ in range(len(q)):
r, c = q.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and work[nr][nc] == 1:
work[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
return minutes if fresh == 0 else -1
def topo_order(num_nodes: int, edges: list[tuple[int, int]]) -> list[int]:
adj: list[list[int]] = [[] for _ in range(num_nodes)]
indeg = [0] * num_nodes
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q: deque[int] = deque(i for i in range(num_nodes) if indeg[i] == 0)
order: list[int] = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == num_nodes else []
def has_directed_cycle(num_nodes: int, edges: list[tuple[int, int]]) -> bool:
adj: list[list[int]] = [[] for _ in range(num_nodes)]
for u, v in edges:
adj[u].append(v)
state = [0] * num_nodes
def dfs(u: int) -> bool:
state[u] = 1
for v in adj[u]:
if state[v] == 1 or (state[v] == 0 and dfs(v)):
return True
state[u] = 2
return False
return any(state[i] == 0 and dfs(i) for i in range(num_nodes))
if __name__ == "__main__":
assert minutes_to_rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]]) == 4
assert minutes_to_rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]]) == -1
dag = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
assert topo_order(6, dag) == [4, 5, 2, 0, 3, 1]
assert not has_directed_cycle(6, dag)
assert has_directed_cycle(3, [(0, 1), (1, 2), (2, 0)])
print("minutes_to_rot:", minutes_to_rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]]))
print("topo_order:", topo_order(6, dag))Running this script produces:
minutes_to_rot: 4
topo_order: [4, 5, 2, 0, 3, 1]Complexity Analysis
Let be vertex count (or grid cells) and be edge count:
| Algorithm | Time Complexity | Extra Space | Notes |
|---|---|---|---|
| Multi-source Grid BFS | Each cell enqueued at most once | ||
| Kahn's Topological Sort | Adjacency list + indeg + queue | ||
| 3-Color Directed DFS | Includes call stack depth up to |
Notice that copying grid inside minutes_to_rot keeps the input immutable while remaining space; in tight memory constraints where mutating the input matrix is allowed, you can skip work and save the copy. Similarly, building an adjacency list (O(V + E)) instead of an adjacency matrix (O(V^2)) keeps sparse dependency graphs linear, since a dense matrix wastes memory and scans non-edges on every vertex visit.
Remember to account for stack frames too: Python defaults to a recursion limit around 1,000 frames, so a path graph of 5,000 vertices crashes naive recursive DFS unless you convert to an explicit stack or Kahn's queue.
Common Mistakes and When I Skip Recursive Graph DFS
Four frequent interview bugs show up here:
- Skipping disconnected components: Always loop
for i in range(num_nodes)when starting DFS or buildingindegacross all nodes0..num_nodes - 1; isolated cycles still matter even when node0is acyclic. - Reversing edge direction silently: In prerequisite lists
[course, prereq], draw the directed arrowprereq -> coursesocoursewaits untilindeg[course]hits zero. - Returning `minutes` when `fresh == 0` at start: Guarding the
whileloop withand fresh > 0prevents an extra off-by-one minute on the final already-empty queue wave. - Using a 2-state visited set on directed graphs: Always separate active path (
1) from finished (2) to avoid false cycle positives on diamond merges.
I skip recursive DFS whenever graphs can grow past 1,000 nodes in deep chains in Python, choosing Kahn's queue or an explicit stack instead to prevent RecursionError. And if edges carry positive weights instead of unit weights, swap plain BFS for Dijkstra's priority queue immediately.
Practice Problems
Apply multi-source BFS and Kahn's topological ordering on these two core problems:
- Course Schedule II: Practice building directed prerequisite edges, detecting cycles via emitted vertex count, and returning a valid sequence.
- Rotting Oranges: Practice multi-source queue seeding, level snapshots (
len(q)), and checking unreachable fresh cells at completion.
