Graph Algorithms
Vertices, edges, and the two basic ways to explore a graph.
- store a graph as an adjacency list or matrix and choose between them
- trace BFS and DFS and say what each one computes
- use BFS/DFS for reachability, components and fewest-move problems
- state the O(n + m) bound and why
Graphs: vertices and edges
A graph G = (V, E) is a set of vertices (nodes) and a set of edges joining pairs of vertices. Graphs model road maps, social networks, the web, course prerequisites, circuits and game states. In an undirected graph an edge {u, v} works in both directions; in a directed graph (digraph) an edge (u, v) goes from u to v only. A weighted graph attaches a number (distance, cost) to each edge.
| Term | Meaning |
|---|---|
| path | a sequence of vertices where consecutive ones are joined by an edge |
| cycle | a path that starts and ends at the same vertex (without reusing edges) |
| connected | every vertex can be reached from every other (undirected) |
| degree | number of edges at a vertex (in-degree / out-degree for digraphs) |
| tree | connected graph with no cycle: n vertices, n − 1 edges |
| DAG | directed acyclic graph |
We write n = |V| for vertices and m = |E| for edges. In a simple graph m ≤ n(n−1)/2, so m = O(n²). A graph with m close to n is sparse; with m close to n² it is dense.
A simple undirected graph has 6 vertices. What is the largest number of edges it can have?
Representing a graph
| Adjacency matrix | Adjacency list | |
|---|---|---|
| Storage | n × n table of 0/1 (or weights): Θ(n²) | for each vertex, list of neighbours: Θ(n + m) |
| Is (u, v) an edge? | O(1) | O(degree of u) |
| List all neighbours of u | O(n) | O(degree of u) |
| Best for | dense graphs | sparse graphs (most real ones) |
We will nearly always use adjacency lists, stored as a dictionary from vertex to list of neighbours. For an undirected edge {u, v}, v appears in u's list and u in v's.
A social network has 10⁶ users, each with about 100 friends. Which representation is practical?
The graph has m undirected edges. What is printed?
adj = {0: [1, 2], 1: [0], 2: [0, 3], 3: [2]}
print(sum(len(v) for v in adj.values()))Breadth-first search (BFS)
Question: which vertices can I reach from vertex s, and what is the fewest number of edges needed to reach each of them?
BFS explores in layers: first s, then everything one edge away, then two edges away, and so on. It keeps a queue of discovered vertices. When it removes a vertex from the queue, it looks at all neighbours and enqueues those it has not seen before.
- the set of vertices reachable from
s - the shortest path length (fewest edges) to each one, in
dist - the actual shortest paths, by following
parentback tos(a BFS tree)
Running time
Each vertex is enqueued once and each adjacency list is scanned once, so BFS takes O(n + m) with adjacency lists — but O(n²) with an adjacency matrix, since scanning a row costs n.
What order does BFS visit the vertices?
from collections import deque
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
seen, q, order = {0}, deque([0]), []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
if v not in seen:
seen.add(v)
q.append(v)
print(order)BFS from s assigns dist[v] = 3 to a vertex. This means…
Which edge-weight situation is BFS suited for?
Depth-first search (DFS)
DFS explores like a person in a maze: go as deep as possible along one path, and when stuck backtrack to the most recent vertex with an unexplored neighbour. It uses recursion (or an explicit stack).
Record pre[u] when DFS enters a vertex and post[u] when it leaves, using one global counter. These numbers reveal structure: v is a descendant of u in the DFS tree exactly when pre[u] < pre[v] < post[v] < post[u].
| BFS | DFS | |
|---|---|---|
| Data structure | queue | stack / recursion |
| Explores | layer by layer | deep first, then backtracks |
| Shortest edge-count paths | yes | no |
| Time (adjacency lists) | O(n + m) | O(n + m) |
What order does DFS visit the vertices?
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
seen, order = set(), []
def go(u):
seen.add(u)
order.append(u)
for v in adj[u]:
if v not in seen:
go(v)
go(0)
print(order)Python raises RecursionError when DFS is run on a path-shaped graph with 10⁵ vertices. Why?
What can we do with BFS and DFS?
Connected components
Run a search from any unvisited vertex, mark everything reached as one component, and repeat. Total time O(n + m).
Cycle detection (undirected)
During a search, if we meet a visited vertex that is not the parent we came from, we have found a cycle. A connected graph with m = n − 1 edges is a tree and has no cycle; one with m ≥ n must contain a cycle.
Shortest path in a maze / word ladder
Whenever each move costs one step, model states as vertices and moves as edges, then BFS gives the minimum number of moves.
Your turn. Build any graph — drag vertices, add edges, delete things — and run BFS or DFS on your graph. Try a disconnected graph, a long path, a star, a cycle.
You want the minimum number of moves for a robot on a grid with obstacles. Best choice?
A connected undirected graph has 10 vertices and 10 edges. It…
Which problems can BFS or DFS solve in O(n + m)?
Chapter challenge — Week 4
Which representation makes 'list all neighbours of u' cost only deg(u)?
In the Week 4 graph (code above), what does this print?
# the undirected graph drawn in the visualiser below (vertices 0..6)
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (4, 5), (3, 5), (4, 6), (5, 6)]
n = 7
adj = {v: [] for v in range(n)}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
for v in adj:
adj[v].sort()
from collections import deque
dist = {0: 0}
q = deque([0])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
print(dist[6])What is the DFS visit order from vertex 0 (sorted adjacency lists)?
# the undirected graph drawn in the visualiser below (vertices 0..6)
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (4, 5), (3, 5), (4, 6), (5, 6)]
n = 7
adj = {v: [] for v in range(n)}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
for v in adj:
adj[v].sort()
order, seen = [], set()
def go(u):
seen.add(u)
order.append(u)
for v in adj[u]:
if v not in seen:
go(v)
go(0)
print(order)Order the steps of BFS.
A tree has 12 vertices. How many edges does it have?
What is the running time of BFS on a graph stored as adjacency lists?
Pick the true statements.
In an undirected graph, the degrees are 3, 2, 2, 1. How many edges are there?
Practice on LeetCode
BFS, DFS, components and fewest-moves problems.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Flood Fill ↗ | Easy | DFS/BFS on a grid | |
| Find if Path Exists in Graph ↗ | Easy | reachability | |
| Number of Islands ↗ | Medium | connected components on a grid | |
| Number of Provinces ↗ | Medium | components from an adjacency matrix | |
| Rotting Oranges ↗ | Medium | multi-source BFS by layers | |
| Shortest Path in Binary Matrix ↗ | Medium | BFS for the fewest steps | |
| Clone Graph ↗ | Medium | traversal with a visited map | |
| Binary Tree Level Order Traversal ↗ | Medium | BFS by levels | |
| Is Graph Bipartite? ↗ | Medium | BFS/DFS two-colouring | |
| Word Ladder ↗ | Hard | BFS on an implicit graph of words |
Key takeaways
- A graph is vertices + edges; prefer adjacency lists (Θ(n + m)) over matrices (Θ(n²)) unless the graph is dense.
- BFS: queue, explores by layers, gives fewest-edge distances. DFS: stack/recursion, explores deep then backtracks. Both are O(n + m).
- Searches answer reachability, connected components, cycle detection, and (BFS) unweighted shortest paths.
- Sum of degrees is 2m; a tree on n vertices has n − 1 edges.