Graph Data Structures (DSA #20)
Trees are graphs with no cycles and a clear hierarchy. The moment relationships become many-to-many — friends, roads, dependencies, web links — you need a graph: a set of vertices and the edges between them. Almost every “network” question reduces to two traversals, BFS and DFS, plus a handful of patterns on top. Learn those and most graph problems become variations on a theme.
This chapter covers graph terminology, the two standard representations, both traversals, connectivity, cycle detection, topological sort, and grid traversal.
Terminology
- Vertices (V) and edges (E); a graph is \(G = (V, E)\).
- Directed edges have a direction (follows, depends-on); undirected edges do not (friendship, road).
- Weighted edges carry a cost (distance, price).
- Degree — number of incident edges (in-degree + out-degree for directed).
- Path — a sequence of connected vertices; cycle — a path returning to its start.
- DAG — a directed acyclic graph; the home of dependency ordering.
- Connected — every vertex reachable from every other (undirected); strongly connected for directed.
The cost of a graph algorithm is usually \(O(V + E)\) for traversal, or \(O(E \log V)\) when a heap is involved.
Representation: list vs matrix
Adjacency list — for each vertex, a list of its neighbours. Space \(O(V + E)\), ideal for sparse graphs (most real graphs are sparse).
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C"],
}
Adjacency matrix — a \(V \times V\) grid where m[u][v] = 1 (or the weight) if there is an edge. Space \(O(V^2)\), but edge lookup and weight checks are \(O(1)\). Use it when the graph is dense or when you repeatedly test “is there an edge?”.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!25] (A) at (0,0) {A};
\node[n, fill=blue!12] (B) at (2.0,0.5) {B};
\node[n, fill=blue!12] (C) at (2.0,-0.9) {C};
\node[n, fill=green!16] (D) at (3.8,0) {D};
\draw[a] (A) -- (B); \draw[a] (A) -- (C); \draw[a] (B) -- (D); \draw[a] (C) -- (D);
\node[font=\small\ttfamily, anchor=west, align=left] at (4.6,0.4) {A: [B, C]\\B: [A, D]\\C: [A, D]\\D: [B, C]};
\end{tikzpicture}
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Space | \(O(V + E)\) | \(O(V^2)\) |
| Iterate neighbours | \(O(\deg)\) | \(O(V)\) |
| Test an edge | \(O(\deg)\) | \(O(1)\) |
| Best for | sparse graphs | dense graphs |
Edge lists ([(u, v, w), ...]) are a third form, useful when you sort edges (Kruskal, Chapter 22).
Breadth-first search
BFS explores level by level using a queue (Chapter 5). It finds shortest paths in unweighted graphs and gives the distance in edges from the source.
from collections import deque
def bfs(graph, start):
dist = {start: 0}
q = deque([start])
while q:
node = q.popleft()
for nb in graph[node]:
if nb not in dist:
dist[nb] = dist[node] + 1
q.append(nb)
return dist
Mark a node as visited when you enqueue it, not when you dequeue it — otherwise the same node can be added multiple times, inflating work and distances.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.66cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!30] (s) at (0,0) {0};
\node[n, fill=cyan!25] (a) at (-1.6,-1) {1}; \node[n, fill=cyan!25] (b) at (1.6,-1) {2};
\node[n, fill=green!18] (c) at (-2.4,-2) {3}; \node[n, fill=green!18] (d) at (-0.8,-2) {4};
\node[n, fill=green!18] (e) at (0.8,-2) {5};
\draw[a] (s) -- (a); \draw[a] (s) -- (b);
\draw[a] (a) -- (c); \draw[a] (a) -- (d); \draw[a] (b) -- (e);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.6) {distance 0, then 1, then 2: BFS layers};
\end{tikzpicture}
Depth-first search
DFS goes as deep as possible before backtracking, using recursion or an explicit stack. It is the natural tool for path existence, cycle detection, topological sort, and connected components.
def dfs(graph, node, seen=None):
if seen is None:
seen = set()
seen.add(node)
for nb in graph[node]:
if nb not in seen:
dfs(graph, nb, seen)
return seen
Its space cost is the recursion depth, up to \(O(V)\) on a long path. Convert to an explicit stack for deep graphs.
def dfs_iter(graph, start):
seen, stack = set(), [start]
while stack:
node = stack.pop()
if node in seen:
continue
seen.add(node)
for nb in graph[node]:
if nb not in seen:
stack.append(nb)
return seen
Connected components
Count how many disjoint groups exist by running a traversal from every unvisited vertex.
def components(graph):
seen, count = set(), 0
for v in graph:
if v not in seen:
count += 1
seen |= dfs(graph, v)
return count
The Union-Find structure (Chapter 17) answers the same question when edges arrive incrementally.
Cycle detection
Undirected graph. A cycle exists if you reach an already-visited vertex that is not the parent you came from.
def has_cycle_undirected(graph, node, parent, seen):
seen.add(node)
for nb in graph[node]:
if nb not in seen:
if has_cycle_undirected(graph, nb, node, seen):
return True
elif nb != parent:
return True
return False
Directed graph. Use a recursion colour set: a cycle exists if DFS reaches a node on the current recursion stack (a “grey” node).
def has_cycle_directed(graph):
WHITE, GREY, BLACK = 0, 1, 2
color = {v: WHITE for v in graph}
def visit(u):
color[u] = GREY
for v in graph[u]:
if color[v] == GREY:
return True # back edge -> cycle
if color[v] == WHITE and visit(v):
return True
color[u] = BLACK
return False
return any(color[v] == WHITE and visit(v) for v in graph)
Topological sort
A topological order lists vertices so every edge points forward — the order to run tasks with dependencies. It exists only for a DAG. Kahn’s algorithm repeatedly removes a vertex with in-degree zero, using a queue.
from collections import deque
def topo_sort(graph, indegree):
q = deque([v for v in graph if indegree[v] == 0])
order = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
q.append(v)
return order if len(order) == len(graph) else None # None = cycle
If the result is shorter than \(V\), the graph has a cycle — topological sort doubles as cycle detection for directed graphs.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum width=1.0cm, minimum height=0.6cm, font=\small\bfseries},
a/.style={->, thick}]
\node[n, fill=green!18] (a) at (0,0) {A};
\node[n, fill=green!18] (b) at (1.6,0.8) {B};
\node[n, fill=blue!12] (d) at (3.2,0.8) {D};
\node[n, fill=green!18] (c) at (1.6,-0.8) {C};
\node[n, fill=blue!12] (e) at (3.2,-0.8) {E};
\draw[a] (a) -- (b); \draw[a] (a) -- (c); \draw[a] (b) -- (d); \draw[a] (c) -- (e);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.6,-1.4) {A B C D E: every edge points forward};
\end{tikzpicture}
Grid traversal (island problems)
A 2D grid is an implicit graph: each cell connects to its four neighbours. Number-of-islands and friends are just DFS/BFS with bounds checking.
def num_islands(grid):
rows, cols = len(grid), len(grid[0])
def sink(r, c):
if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
return
grid[r][c] = "0" # mark visited
sink(r+1, c); sink(r-1, c); sink(r, c+1); sink(r, c-1)
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
count += 1
sink(r, c)
return count
Pitfalls
- Marking visited late in BFS. Mark on enqueue, or nodes are added repeatedly.
- Using adjacency-matrix space for a sparse graph. \(O(V^2)\) memory explodes for large \(V\); prefer lists.
- Recursing too deep in DFS. A path of \(n\) vertices overflows the stack; use an explicit stack.
- Confusing the two cycle tests. Undirected uses “parent”, directed uses recursion-stack colouring.
- Assuming topological order is unique. Many valid orders exist; any valid one is correct.
- Forgetting the graph may be disconnected. Loop over all vertices, not just from the start.
Why does BFS give shortest paths only on unweighted graphs? What is the difference between the undirected and directed cycle-detection tests?
ASolution
BFS expands in order of edge count, so the first time it reaches a vertex it has used the fewest edges; with weights, fewer edges does not mean lower cost. Undirected cycle detection triggers on a visited neighbour that is not the parent; directed detection triggers on a neighbour still on the current recursion stack (a back edge).
Next: Shortest Path Algorithms (DSA #21) — weighted routes: Dijkstra, Bellman-Ford, and A*.