Graphs
Vertices and edges — the most general structure. Terminology, representations, and how to choose between them.
A graph G = (V, E) is a set of vertices (nodes) and edges connecting pairs of them. Trees and linked lists are special cases. Road maps, social networks, the web, package dependencies, network routers, state machines and course prerequisites are all graphs.
Vocabulary
| Term | Meaning |
|---|---|
| Directed / undirected | Edges have a direction (A → B) or not (A — B) |
| Weighted | Edges carry a cost: distance, latency, capacity |
| Degree | Number of edges at a vertex (in-degree / out-degree if directed) |
| Path | A sequence of vertices joined by edges |
| Cycle | A path that returns to its start |
| Connected | Every vertex reachable from every other (undirected) |
| Strongly connected | Every vertex reachable from every other along directions |
| DAG | Directed acyclic graph — dependencies, schedules, build systems |
| Sparse / dense | E ≈ V vs E ≈ V² |
Representations
Adjacency list
For each vertex, a list of its neighbours. The default choice — most real graphs are sparse.
Adjacency matrix
A V × V grid where m[u][v] = 1 (or the weight) if there's an edge. O(1) edge lookup, but O(V²) memory.
Edge list
Just a list of (u, v, w) tuples. Natural for Kruskal's MST and Bellman-Ford.
| Adjacency list | Adjacency matrix | Edge list | |
|---|---|---|---|
| Memory | O(V + E) | O(V²) | O(E) |
| Is (u, v) an edge? | O(deg u) | O(1) | O(E) |
| Iterate neighbours of u | O(deg u) | O(V) | O(E) |
| Iterate all edges | O(V + E) | O(V²) | O(E) |
| Best for | Sparse graphs (most) | Dense graphs, Floyd-Warshall | Sorting edges |
// Build an adjacency list from an edge list
int n = 5;
int[][] edges = {{0,1},{0,2},{1,2},{1,3},{2,4},{3,4}};
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
adj.get(e[1]).add(e[0]); // omit for directed graphs
}
// Weighted: store pairs (neighbour, weight)
List<List<int[]>> wadj = new ArrayList<>();
// Adjacency matrix
boolean[][] m = new boolean[n][n];
for (int[] e : edges) m[e[0]][e[1]] = m[e[1]][e[0]] = true;from collections import defaultdict
edges = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 4)]
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # omit for directed graphs
# Weighted
wadj = defaultdict(list) # wadj[u] = [(v, w), ...]
# Adjacency matrix
n = 5
m = [[0] * n for _ in range(n)]
for u, v in edges:
m[u][v] = m[v][u] = 1const n = 5;
const edges = [[0, 1], [0, 2], [1, 2], [1, 3], [2, 4], [3, 4]];
const adj: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u); // omit for directed graphs
}
// Weighted: adjW[u] = [[v, w], ...]
const adjW: [number, number][][] = Array.from({ length: n }, () => []);
// Adjacency matrix
const m = Array.from({ length: n }, () => new Array(n).fill(0));
for (const [u, v] of edges) m[u][v] = m[v][u] = 1;Traversal
The two fundamental ways to explore a graph — breadth-first (queue) and depth-first (stack/recursion) — both run in O(V + E). Always keep a visited set: unlike trees, graphs have cycles.
The algorithm map
| Problem | Algorithm | Lesson |
|---|---|---|
| Reachability, connected components | BFS / DFS | Graph traversal |
| Shortest path, unweighted | BFS | Graph traversal |
| Shortest path, non-negative weights | Dijkstra | Shortest paths |
| Shortest path, negative weights | Bellman-Ford | Shortest paths |
| All-pairs shortest paths | Floyd-Warshall | Shortest paths |
| Cheapest way to connect all nodes | Kruskal / Prim | MST |
| Order tasks with dependencies | Topological sort | Topological sort & SCC |
| Dynamic connectivity | Union-Find | Union-Find |
| Max flow / bipartite matching | Ford-Fulkerson, Edmonds-Karp | Network flow |
- Graphs model relationships: V vertices, E edges, optionally directed and weighted.
- Use adjacency lists by default: O(V + E) memory and fast neighbour iteration.
- Traversal is O(V + E) and needs a visited set.
- Recognise implicit graphs: grids, word ladders, state spaces.
QHow do you detect a cycle in a directed vs an undirected graph?medium
Undirected: DFS and report a cycle if you reach a visited vertex that isn't your parent (or use Union-Find: an edge joining two vertices already in the same set). Directed: DFS with three colours — white (unvisited), grey (on the current recursion stack), black (done); reaching a grey vertex means a back edge, i.e. a cycle. Kahn's topological sort also detects it: if not all vertices are output, there's a cycle.
QNumber of islands in a grid.medium
Treat land cells as vertices connected to their 4 land neighbours. For every unvisited land cell, increment the count and flood-fill (BFS/DFS) to mark its whole island. O(rows × cols).
QIs a graph bipartite?medium
Try to 2-colour it with BFS/DFS: colour the start 0, neighbours 1, and so on. If an edge ever joins two vertices of the same colour, it's not bipartite (equivalently, it has an odd cycle).