Graph Algorithms
Traversal, shortest paths, and spanning trees — with the one to reach for in each case.
A graph is a set of nodes joined by edges, which may be directed and may carry weights: roads, dependencies, friendships, grid cells, puzzle states. Most graph problems are one of a few questions — can I reach it, what is the cheapest way there, what order respects the dependencies, which edges connect everything most cheaply.
Complexities use V for vertices and E for edges and assume an adjacency list. Choosing a shortest-path algorithm is mostly about the edge weights: none, non-negative, or possibly negative.
Representations
- Adjacency list
O(V + E)space, neighbors inO(degree)— the default choice- Adjacency matrix
O(V²)space,O(1)edge check — dense graphs and Floyd–Warshall- Edge list
(u, v, w)triples — exactly what Kruskal and Bellman–Ford iterate over- Grid as a graph
- cells are nodes and the 4 (or 8) neighbors are edges — no graph to build
- Implicit graph
- states plus moves (word ladder, puzzles): generate neighbors on the fly
Traversal
- BFS
- queue, level by level ·
O(V + E)· shortest path by edge count on unweighted graphs - DFS
- stack / recursion ·
O(V + E)· cycle detection, topological sort, connected components - Topological sort
- DFS post-order or Kahn (BFS on in-degrees) ·
O(V + E)· DAGs only — order tasks by dependency - Mark visited on enqueue
- not on dequeue — otherwise a node can enter the queue many times
- Multi-source BFS
- start the queue with every source at distance 0 — nearest exit, rotting oranges
- 0-1 BFS
- a deque: weight-0 edges to the front, weight-1 to the back ·
O(V + E) - Bidirectional BFS
- search from both ends and meet in the middle — far fewer nodes on big graphs
- Iterative DFS
- an explicit stack avoids recursion limits (about 1,000 frames in Python)
- Connected components
- start a BFS/DFS from each unvisited node; the number of starts is the count
Shortest paths
- BFS (unweighted)
O(V + E)· fewest edges from a source — no weights- Dijkstra
- single-source, non-negative weights ·
O((V + E) log V)with a binary heap - Bellman–Ford
- single-source, handles negative edges · detects negative cycles ·
O(V·E) - Floyd–Warshall
- all-pairs, negatives OK (no negative cycle) ·
O(V³)· spaceO(V²) - A*
- Dijkstra + heuristic · faster to a single target when a good admissible heuristic exists
- Stale heap entries
- Dijkstra with
heapq: skip a popped node whose distance has since improved - DAG shortest path
- relax edges in topological order ·
O(V + E), negative weights fine - Negative-cycle check
- a V-th Bellman–Ford pass that still relaxes an edge proves one exists
- Johnson’s algorithm
- all pairs on sparse graphs with negative edges: reweight, then Dijkstra from each node
Cycles & structure
- Cycle (directed)
- DFS with three colors: an edge back to a node still on the stack is a cycle
- Cycle (undirected)
- union-find: an edge whose ends are already connected; or DFS ignoring the parent
- Kahn’s cycle check
- if fewer than V nodes come out of a topological sort, there is a cycle
- Bipartite check
- BFS 2-coloring; an edge between two same-colored nodes means an odd cycle
- Strongly connected comps
- Tarjan or Kosaraju ·
O(V + E)— groups of mutually reachable nodes - Bridges & articulation pts
- Tarjan low-link: edge u–v is a bridge when
low[v] > disc[u]
Minimum spanning tree
- Kruskal
- sort edges + union-find, add if no cycle ·
O(E log E)· great for sparse graphs - Prim
- grow the tree from a node with a min-heap ·
O((V + E) log V)· great for dense graphs - Union-find
- near-constant union and find with path compression and union by rank or size
- Cut property
- the lightest edge crossing any cut is in some MST — why both greedy algorithms work
Flows, matching & tours
- Max flow
- Edmonds–Karp (BFS augmenting paths)
O(V·E²); DinicO(V²·E) - Max-flow min-cut
- the maximum flow equals the capacity of the smallest cut separating source and sink
- Bipartite matching
- Hopcroft–Karp
O(E·√V), or max flow with unit capacities - Eulerian path
- every edge once: 0 or 2 odd-degree vertices (undirected); Hierholzer
O(E) - Hamiltonian path / TSP
- every vertex once: NP-hard; bitmask DP
O(2ⁿ·n²)for small n
Which to use
- Unweighted shortest path
- BFS — fewest edges,
O(V + E) - Non-negative weights
- Dijkstra with a heap
- Negative edges present
- Bellman–Ford (and it flags negative cycles)
- All-pairs shortest paths
- Floyd–Warshall on small/dense graphs
- Cheapest connecting tree
- Kruskal (sparse) or Prim (dense)
- Order with dependencies
- Topological sort (DFS or Kahn)
- Connectivity / cycles
- Union-Find or a DFS
- Edge weights only 0 or 1
- 0-1 BFS with a deque — Dijkstra’s answer without the heap
- Shortest path in a DAG
- topological order plus relaxation — linear, even with negative edges
Worked example: Dijkstra traced on the graph above
Run the heapq recipe from A, with each node’s neighbours listed alphabetically. The heap holds (distance, node) tuples, so ties break on the node name.
pop heap after this pop’s pushes dist changes
(0, A) (1,C) (4,B) B=4 C=1
(1, C) (3,B) (4,B) (6,D) B=3 D=6
(3, B) (4,B) (4,D) (6,D) D=4
(4, B) stale: 4 > dist[B] = 3, skip
(4, D) (6,D) (7,E) E=7
(6, D) stale: 6 > dist[D] = 4, skip
(7, E) empty done- B is first reached at 4 straight from A, then improved to 3 through C. The old
(4, B)stays in the heap, becauseheapqcannot update it. - Seven pops for five nodes: the two extra pops are the stale entries, discarded in one comparison each.
- Record
parent[v] = uwheneverdist[v]improves, and the path falls out backwards: E ← D ← B ← C ← A, total 1 + 2 + 1 + 3 = 7.
Negative weights break the “popped means final” rule. In a directed graph with A→B 1, A→C 3 and C→B −3, textbook Dijkstra finalizes B at 1 before it pops C, yet A→C→B costs 0. The heapq recipe happens to repair this by pushing B again, but re-pushes like that lose the O((V + E) log V) bound. On an undirected graph a negative edge is already a negative cycle: walk it back and forth.
Recipes
BFS on a grid: fewest steps from start to goal
from collections import deque
def shortest_path(grid, start, goal):
rows, cols = len(grid), len(grid[0])
dist = {start: 0}
q = deque([start])
while q:
r, c = q.popleft()
if (r, c) == goal:
return dist[(r, c)]
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 grid[nr][nc] != '#' and (nr, nc) not in dist):
dist[(nr, nc)] = dist[(r, c)] + 1 # mark on enqueue
q.append((nr, nc))
return -1 # goal unreachableThe first time BFS reaches a cell is along a shortest path, so the dist map doubles as the visited set. Use deque.popleft(); list.pop(0) makes BFS quadratic.
Dijkstra with heapq
import heapq
def dijkstra(graph, src): # graph: {u: [(v, weight), ...]}
dist = {src: 0}
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float('inf')):
continue # stale entry: u was settled cheaper
for v, w in graph.get(u, []):
nd = d + w
if nd < dist.get(v, float('inf')):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return distheapq has no decrease-key, so the same node is pushed again with a better distance and the old entry is skipped when popped. Weights must be non-negative.
Topological sort with cycle detection (Kahn)
from collections import deque
def topo_sort(n, edges): # edges: (before, after)
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
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) == n else None # None: there is a cycleA node is released once everything it depends on is done. Nodes on a cycle never reach in-degree zero, which is how the length check detects a circular dependency.
Union-find, and Kruskal on top of it
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already connected: edge would close a cycle
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
# Kruskal: sort the edges by weight and keep those where union() returns True
dsu = DSU(n)
mst = [(w, u, v) for w, u, v in sorted(edges) if dsu.union(u, v)]Path halving plus union by size keeps the trees almost flat, so each operation is effectively constant time. The MST is complete once it holds V − 1 edges.
Bipartite check by BFS 2-coloring
from collections import deque
def is_bipartite(adj): # adj: list of neighbor lists
color = [-1] * len(adj)
for s in range(len(adj)): # cover every component
if color[s] != -1:
continue
color[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if color[v] == -1:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False # same colors meet: odd cycle
return TrueThe outer loop matters: a graph can be disconnected, and starting from node 0 alone would leave other components unchecked.
When to use it, and when not
Model a problem as a graph when the data is “things plus connections” and the question is about reaching, ordering or connecting them. Often the graph is never built: grid cells, puzzle states and words one letter apart are all graphs whose neighbours you compute on demand.
- A tree is simpler. With exactly one path between any two nodes, a single DFS answers most questions, and there is no need for a visited set beyond the parent.
- Constraints change the state. “Shortest path using at most k edges” or “with at most one coupon” is a search over
(node, k)pairs, or k rounds of Bellman–Ford that each read only the previous round’s distances. - Longest path is different. Longest simple path is NP-hard in general; only on a DAG does it become a linear pass in topological order.
- The graph does not fit in memory. Billions of edges call for a graph database or a distributed engine, or for an implicit graph you never store.
Trade-offs and limits
The representation sets the memory bill; the algorithm sets the time. Rough operation counts for V = 1,000 nodes and E = 10,000 edges:
| Algorithm | Formula | ≈ operations | Gives up |
|---|---|---|---|
| BFS | V + E | 11,000 | Weights |
| Dijkstra | (V + E) log V | 110,000 | Negative edges |
| Bellman–Ford | V · E | 10,000,000 | Speed, for negatives and cycle detection |
| Floyd–Warshall | V³ | 1,000,000,000 | Scale, for every pair at once |
An adjacency matrix for 100,000 nodes would need 10¹⁰ cells, while the list holds only the edges that exist. BFS keeps a whole frontier in memory, which on a wide graph can be most of the nodes; DFS keeps one path, which on a long chain can be all of them.
Common mistakes
- Marking Dijkstra nodes done when pushed. A node is final only when it is popped with its current distance. Marking it on push freezes the first, possibly longer, route — B would be stuck at 4 in the example above.
- One direction for an undirected edge. Append
vtoadj[u]andutoadj[v]; otherwise half the graph is unreachable and BFS reports “no path”. - The wrong loop order in Floyd–Warshall. The intermediate node
kmust be the outermost loop. Withkinsideiandj, a pair is finalized before all of its routes have been considered. - A visited list instead of a set.
if cell not in visitedon a list isO(n), which turns a grid BFS quadratic. Use a set or a 2-D boolean array. - Reversing pre-order for a topological sort. The DFS version needs nodes in the order they finish, reversed. Pre-order can place a node before something it depends on.
Check yourself
Kahn’s algorithm on edges a→b, a→c, b→d, c→d, d→b. What comes out?
Only [a, c]. b and d each keep an incoming edge from the other, so they never reach in-degree 0; 2 < 4 nodes means there is a cycle.
Kruskal on edges (weight, u, v): (1, A, B), (2, B, C), (3, A, C), (4, C, D), (5, B, D). Which edges does it keep, and what is the total?
AB, BC and CD, total 7. AC is rejected because A and C are already connected, and BD for the same reason.
A graph has 6 nodes. How many Bellman–Ford rounds does it need, and what does one more round tell you?
5 rounds (V − 1) settle every shortest path. If a 6th round still lowers a distance, a negative cycle is reachable.
Every edge weighs 0 or 1. Which algorithm gives Dijkstra’s answer in O(V + E)?
0-1 BFS: a deque where a weight-0 edge pushes to the front and a weight-1 edge to the back.
Questions about Graph Algorithms Cheat Sheet
When should I use BFS vs DFS?
Use breadth-first search when you need the shortest path in an unweighted graph or grid, or anything measured in levels or steps, because BFS reaches every node by the fewest possible edges. Use depth-first search for exhaustive exploration: detecting cycles, topological sorting, finding connected components, backtracking over choices, and tree problems where you combine results from children. Both run in O(V + E). BFS keeps a whole frontier in memory, which can be large on wide graphs, while DFS keeps one path, but recursive DFS can overflow the call stack on deep graphs unless you use an explicit stack.
Why doesn't Dijkstra's algorithm work with negative edge weights?
Dijkstra assumes that once it removes the closest unsettled node from the priority queue, that distance is final, since any other route would have to pass through nodes that are already at least as far away. A negative edge breaks the assumption: a longer-looking route can become cheaper after the node was settled, so the answer can be wrong. Variants that re-insert improved nodes may still produce the right answer on some graphs, but they lose the O((V + E) log V) guarantee and never terminate on a negative cycle. Use Bellman-Ford, or Johnson for all pairs.
What is the difference between Kruskal's and Prim's algorithm?
Both find a minimum spanning tree and both are greedy, justified by the cut property. Kruskal works edge by edge: it sorts all edges by weight and adds each one that does not create a cycle, using union-find to check, in O(E log E). Prim grows a single tree from a start node, always adding the cheapest edge that leaves the tree, using a priority queue, in O(E log V). Kruskal is simpler on sparse graphs given as an edge list, and it naturally produces a minimum spanning forest when the graph is disconnected. Prim suits dense graphs and adjacency lists.
What is topological sorting used for?
A topological sort orders the nodes of a directed acyclic graph so that every edge points forward, meaning each item appears after everything it depends on. It is how build systems order compilation steps, package managers install dependencies, spreadsheets recalculate cells, schedulers run tasks and course planners order prerequisites. Kahn’s algorithm repeatedly removes nodes with no remaining incoming edges, while the DFS version reverses the post-order. Both run in O(V + E). If the graph contains a cycle no valid order exists, and both algorithms can detect that, which is how circular dependencies get reported.