5. Graphs & Dynamic Programming

Graphs: Grid BFS/DFS, Cycle Detection & Topological Sort

Model networks, grids, and course prerequisites cleanly with adjacency lists in Python: traverse graphs safely with visited sets, find shortest unweighted paths via BFS, and order dependencies with Kahn's Topological Sort.

6 min readUpdated 2026-11-30
In This Lesson
  • Represent directed and undirected graphs cleanly using defaultdict(list)
  • Traverse graphs and 2D grids without infinite loops using a visited set
  • Order prerequisite tasks and detect dependency cycles using Kahn's BFS Topological Sort

Unlike trees, graphs can have cycles, multiple paths between two nodes, and disconnected components. One missing visited check will send your traversal into an infinite loop (or RecursionError)!

Why It Matters: Graphs Model Every Real Network

From social graphs and road maps to package managers (pip / npm dependencies) and 2D game grids, graph problems all run in O(V + E) time (vertices + edges) when represented with an adjacency list (defaultdict(list)) instead of an O(V²) adjacency matrix.

Building an Adjacency List in 3 Lines

python
from collections import defaultdict

graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)
    graph[v].append(u)  # Omit this line for directed graphs!

For 2D grids (islands, mazes, shortest paths), treat each cell (r, c) as a node whose 4 neighbors are (r + dr, c + dc) for (dr, dc) in ((1, 0), (-1, 0), (0, 1), (0, -1))—no adjacency list needed!

Pattern 1: Grid DFS / BFS & The visited Timing Rule

  • Use DFS when counting connected components (Number of Islands), flood-filling regions, or checking reachability.
  • Use BFS (deque) whenever you need the shortest path (minimum steps) on an unweighted graph or grid, because BFS explores outward layer by layer (dist = 0, 1, 2, ...).
Always Mark visited When Enqueueing in BFS, Not When Popping!

If you add (nr, nc) to visited only after popping it from the deque, multiple neighbors at distance d will push the exact same cell into the queue—causing duplicate work and exponential queue blow-up on grids! Mark visited.add((nr, nc)) immediately before q.append(...).

Pattern 2: Kahn's Topological Sort (Prerequisites & Cycle Detection)

Directed Prerequisites DAG & Kahn's Indegree Queue

Course 0

indegree = 0 (Start)

Course 1 (indegree: 1 → 0)
Course 2 (indegree: 1 → 0)

Course 3

indegree: 2 → 1 → 0

Start with indegree == 0 nodes in a deque; removing each node unlocks downstream courses until none remain (or a cycle blocks completion).

Given num_courses tasks with prerequisite edges (course, prereq) meaning prereq -> course, Kahn's Algorithm produces a valid linear build/study order—or detects a cycle:

  1. Compute indegree[v] (how many prerequisites v still waits on).
  2. Enqueue every node with indegree == 0 (no remaining prerequisites).
  3. Pop cur, append to order, decrement indegree[nxt] for each neighbor, and enqueue nxt if indegree[nxt] == 0.
  4. Cycle check: If len(order) < num_courses, at least one cycle prevented nodes from ever reaching indegree == 0!

Step-by-Step Dry-Run Trace: course_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)])

Edges: 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3. Initial indegree = [0, 1, 1, 2].

StepQueue StartPopped (cur)Neighbors DecrementedNewly 0 Enqueuedorder After Step
Init[0]———[]
1[0]0indegree[1]=0, indegree[2]=01, 2[0]
2[1, 2]1indegree[3]=1None[0, 1]
3[2]2indegree[3]=03[0, 1, 2]
4[3]3None—[0, 1, 2, 3]

len(order) == 4 == num_courses → valid schedule! Now imagine edges (0, 1) and (1, 0): indegree = [1, 1], the queue starts empty, and len(order) == 0 < 2 immediately detects the cycle!

Edge Cases to Always Guard Against

  • Empty grid (grid = [] or grid = [[]]): Guard if not grid or not grid[0]: return 0.
  • Disconnected nodes with 0 edges in Topological Sort: Initializing q = deque(i for i in range(num_courses) if indegree[i] == 0) ensures isolated courses are included automatically.
  • Mutating the input grid vs keeping a visited set: Overwriting grid[r][c] = "0" saves O(R·C) space, while visited = set() keeps the caller's input untouched.
Grid DFS Recursion Depth Warning

On a 500 × 500 grid of all "1"s, recursive DFS can hit Python's 1,000-frame recursion limit! For large production grids, convert DFS to an iterative stack (stack = [(r, c)]) or BFS (deque).

Pattern Recognition: Which Graph Algorithm?

Problem SignalBest AlgorithmComplexity
Count connected components / flood fillDFS or BFS with visitedO(V + E)
Shortest path in unweighted graph or gridBFS (deque)O(V + E)
Course schedule, task dependencies, cycle in directed graphKahn's Topological SortO(V + E)
Shortest path with positive edge weightsDijkstra (heapq) (see Lesson 15!)O((V + E) log V)

Try It Yourself in the Playground

Test Number of Islands (Grid DFS) and Kahn's Topological Sort (Course Prerequisites & Cycle Detection) right below:

Python 3Try It Live: Grid Islands DFS & Kahn's Topological Sort
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why should BFS mark a node as visited at the moment it is pushed onto the deque rather than when it is popped?

Quick Checkpoints

Check Your Understanding

In Kahn's Topological Sort algorithm, how do you know the directed graph contains a dependency cycle (impossible schedule)?

Check Your Understanding

Which traversal guarantees finding the shortest path (fewest steps) in an unweighted graph or 2D grid?

Check Your Understanding

What is the time complexity of traversing a graph with V vertices and E edges represented as an adjacency list?