Patterns: graphs
This review of graph problems covers three patterns: a grid is a graph with a vertex per cell, stored as a vector<string> with direction arrays for neighbours; check edge weights before picking a shortest-path algorithm; exam hand calculations use fixed tables.
With graph problems the hard part often isn't the algorithm but seeing that it's a graph and picking the right tool. A map, a maze, a game board, a table of dependencies: behind each are vertices and edges. This lesson takes one kind of question per level: grids, choosing a shortest-path algorithm, the exam's hand calculations, and the formulas for degrees and edges.
Pattern 1: a grid is a graph
In a 2D grid every cell is a vertex, with edges to the cells above, below, left and right (sometimes diagonals too). The edges are never stored: keep the grid in a vector<string> or vector<vector<int>> and work out the neighbours from two direction arrays, dr and dc.
- Counting connected regions (number of islands, regions in an image): scan cell by cell; at land not yet visited, add 1 to the count and DFS from it to "flood" the whole region. This is a flood fill.
- Fewest steps (a maze, a knight's moves): BFS, with a
queue<pair<int, int>>. - Spreading from several starts at once (fire spreading, distance to the nearest exit): put every start in the queue together, then BFS. This is a multi-source BFS.
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6// flood the island containing (r, c) and return its size; g is passed by reference, so the real grid changes7int sink(vector<string>& g, int r, int c) {8 if (r < 0 || r >= (int)g.size() || c < 0 || c >= (int)g[0].size() || g[r][c] != '1')9 return 0;10 g[r][c] = '0'; // turn it into water so we never come back11 return 1 + sink(g, r + 1, c) + sink(g, r - 1, c) + sink(g, r, c + 1) + sink(g, r, c - 1);12}13 14int main() {15 vector<string> g = {16 "11001",17 "10011",18 "00100",19 "10110",20 };21 int count = 0;22 for (int r = 0; r < (int)g.size(); r++)23 for (int c = 0; c < (int)g[0].size(); c++)24 if (g[r][c] == '1') {25 count++;26 int cells = sink(g, r, c);27 cout << "island " << count << " starts at (" << r << ", " << c << "), " << cells << " cells\n";28 }29 cout << count << " islands in all\n";30 return 0;31}
island 1 starts at (0, 0), 3 cells island 2 starts at (0, 4), 3 cells island 3 starts at (2, 2), 3 cells island 4 starts at (3, 0), 1 cells 4 islands in all
Check "out of bounds" and "unvisited land" first, then recurse: that way none of the four calls needs its own check. Turning land into '0' counts as "visited" and saves a visited array (if the problem forbids changing the input, use a vector<vector<bool>>). g must be passed by reference: with vector<string> g, every call copies the whole grid and changes only the copy. g.size() is an unsigned size_t; convert it to int before comparing it with an r that may be −1.
1 is land and 0 is water. Counting only up, down, left and right as connected, how many islands does this grid have?
11 0 120 1 031 0 1
Number of islands
✓Complete sink: return if out of bounds or not land (g[r][c] != '1'); otherwise turn it into '0' and recurse in the four directions.
4
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6void sink(vector<string>& g, int r, int c) {7 // return if out of bounds or not '1'; otherwise g[r][c] = '0', then sink up, down, left and right8}9 10int main() {11 vector<string> g = {12 "110010",13 "100011",14 "001000",15 "011001",16 "000011",17 };18 int count = 0;19 for (int r = 0; r < (int)g.size(); r++)20 for (int c = 0; c < (int)g[0].size(); c++)21 if (g[r][c] == '1') {22 count++;23 sink(g, r, c);24 }25 cout << count << "\n";26 return 0;27}
Rotting oranges
✓2 is a rotten orange, 1 a fresh one, 0 an empty cell. Every minute, a rotten orange rots the fresh ones above, below, left and right of it. Multi-source BFS: all rotten oranges go in the queue together at the start (time 0). Complete the part of the BFS that looks in the four directions; return -1 if some fresh orange can never rot.
6 -1
1#include <iostream>2#include <vector>3#include <queue>4#include <utility>5using namespace std;6 7int minutes(const vector<vector<int>>& g) {8 int R = g.size(), C = g[0].size();9 vector<vector<int>> t(R, vector<int>(C, -1));10 queue<pair<int, int>> q;11 int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};12 for (int r = 0; r < R; r++)13 for (int c = 0; c < C; c++)14 if (g[r][c] == 2) {15 t[r][c] = 0;16 q.push({r, c});17 }18 while (!q.empty()) {19 int r = q.front().first, c = q.front().second;20 q.pop();21 // four directions: in bounds, a fresh orange (1), t still -1: t = t[r][c] + 1, push it22 }23 int most = 0;24 for (int r = 0; r < R; r++)25 for (int c = 0; c < C; c++) {26 if (g[r][c] == 1 && t[r][c] == -1) return -1;27 if (t[r][c] > most) most = t[r][c];28 }29 return most;30}31 32int main() {33 vector<vector<int>> a = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}};34 vector<vector<int>> b = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {1, 0, 0, 1}};35 cout << minutes(a) << "\n" << minutes(b) << "\n";36 return 0;37}
Pattern 2: shortest paths, look at the weights first
| What the problem looks like | Use | Time |
|---|---|---|
| No weights, or every edge the same length (how many steps, how many changes) | BFS, queue | O(n + e) |
| Weights only 0 and 1 | 0-1 BFS: a deque, push_front for 0 edges, push_back for 1 edges | O(n + e) |
| One source, all weights ≥ 0 | Dijkstra (an array when n is small, priority_queue for a sparse graph) | O(n²) or O((n + e) log n) |
| One source, negative edges | Bellman-Ford / SPFA | O(n·e) |
| A directed acyclic graph | relax once in topological order | O(n + e) |
| All pairs, n only a few hundred | Floyd | O(n³) |
Easy mistakes:
- Using Dijkstra with negative edges: the counterexample from the Dijkstra lesson gives a wrong answer.
- Using BFS for shortest paths in a weighted graph: fewer edges is not always shorter.
- Leaving out
greaterin thepriority_queue: the default is a max-heap, which pops the farthest first. - Putting k inside in Floyd's three loops: in
d[i][j] = min(d[i][j], d[i][k] + d[k][j]), k must be outermost. It means "the shortest path using only 0 to k as stopovers", and the case for k − 1 must be complete first. - INF as
INT_MAX:INF + woverflows into a negative number. Use a billion; two of them added still fit in an int. - Bellman-Ford on an undirected graph: one negative edge is a negative cycle (go there and back and it gets shorter).
A directed acyclic graph where a few edges have negative weights: shortest paths from one start to every vertex, in O(n + e). What do you use?
Floyd: shortest paths for every pair
✓Complete Floyd's three loops: k outermost; when d[i][k] + d[k][j] is smaller, update d[i][j]. (INF is a billion, so two INFs added don't overflow an int.)
0 5 8 9 6 0 3 4 3 5 0 1 2 4 7 0
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8 int n = 4;9 vector<vector<int>> d(n, vector<int>(n, INF));10 for (int i = 0; i < n; i++) d[i][i] = 0;11 d[0][1] = 5; d[0][3] = 10; d[1][2] = 3;12 d[2][3] = 1; d[3][0] = 2; d[3][1] = 4; // directed edges13 // for k, for i, for j: if d[i][k] + d[k][j] < d[i][j], update it14 for (int i = 0; i < n; i++) {15 for (int j = 0; j < n; j++)16 cout << d[i][j] << " ";17 cout << "\n";18 }19 return 0;20}
Pattern 3: exam hand calculations
Exam graph questions mostly say "write the algorithm's steps". A few fixed formats:
The Dijkstra table: one row per round with the current dist of every unsettled vertex; circle the smallest (it is settled this round) and relax with it in the next row. With the graph from the Dijkstra lesson (0–1:7, 0–2:2, 2–1:3, 1–3:4, 2–4:9, 3–4:1, 3–5:6, 4–5:3), from 0:
The order of Prim and Kruskal: for Prim, write "from v, the edges added in turn", each time the shortest edge with one end in the tree and one outside; for Kruskal, write "by weight from small to large: take, skip, take…", and for each skip say which edges it would make a cycle with.
All topological orders: at each step try every vertex with in-degree 0 in turn; drawn as a tree, the number of leaves is the number of orders. This program lists them all by backtracking:
1#include <iostream>2#include <vector>3using namespace std;4 5int n = 5, total = 0;6vector<vector<int>> adj(n);7vector<int> indeg(n, 0), order;8vector<bool> used(n, false);9 10void all() {11 if ((int)order.size() == n) {12 total++;13 for (int v : order) cout << v << " ";14 cout << "\n";15 return;16 }17 for (int v = 0; v < n; v++)18 if (!used[v] && indeg[v] == 0) { // try every vertex with in-degree 019 used[v] = true;20 order.push_back(v);21 for (int x : adj[v]) indeg[x]--;22 all();23 for (int x : adj[v]) indeg[x]++; // undo, try the next one24 order.pop_back();25 used[v] = false;26 }27}28 29int main() {30 auto add = [](int u, int v) { adj[u].push_back(v); indeg[v]++; };31 add(0, 2); add(1, 2); add(2, 3); add(2, 4); // 0 and 1 before 2, 2 before 3 and 432 all();33 cout << total << " in all\n";34 return 0;35}
0 1 2 3 4 0 1 2 4 3 1 0 2 3 4 1 0 2 4 3 4 in all
Directed edges A → B, A → C, A → D, B → E. How many topological orders are there?
Pattern 4: formulas for degrees and edges
Exam multiple-choice questions love a handful of formulas about degrees and edge counts. Each one comes from simple counting: every edge has two ends, for example, so the degrees of an undirected graph add up to 2e.
| The question | The answer |
|---|---|
| Sum of all degrees in an undirected graph | 2e |
| Sum of in-degrees, sum of out-degrees in a directed graph | both e |
| Edges in a complete undirected graph on n vertices | n(n − 1) / 2 (complete directed: n(n − 1)) |
| Fewest edges in a connected graph on n vertices | n − 1 (a spanning tree) |
| Fewest edges on n vertices that guarantee it is connected | (n − 1)(n − 2) / 2 + 1 |
| Number of 1s in the adjacency matrix | undirected 2e, directed e |
Edge nodes in the adjacency list (total elements in a vector<vector<int>>) | undirected 2e, directed e |
| Trees in a forest with n vertices and e edges | n − e |
The idea behind "guarantee connected": connect n − 1 vertices to each other completely, using (n − 1)(n − 2) / 2 edges, and the last vertex is still alone; one more edge must reach it.
An undirected graph on 7 vertices (no repeated edges): at least how many edges guarantee it's connected, however they're placed?
An undirected graph has 10 edges. What do the degrees of all its vertices add up to, and how many 1s are in its adjacency matrix?
a[u][v] and a[v][u], so that's 20 ones too. Only a directed graph has e.Summary
Three graph patterns
- A grid is a graph: work out neighbours from direction arrays; flood regions with DFS to count them, BFS for fewest steps
- Spreading from several starts: put them all in the queue first, then BFS
- Shortest paths, weights first: none BFS, 0/1 a deque, non-negative Dijkstra, negative Bellman-Ford, all pairs Floyd
- Exams: Dijkstra's table settles one per round; degrees sum to 2e; guaranteed connected at (n − 1)(n − 2) / 2 + 1
1int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};2for (int k = 0; k < 4; k++) {3 int nr = r + dr[k], nc = c + dc[k];4 if (nr >= 0 && nr < R && nc >= 0 && nc < C && …) q.push({nr, nc});5}
Chapter 5 quick check
Five questions: BFS and DFS on the same adjacency list, the order Kahn's algorithm gives, the distances from the priority_queue Dijkstra, and Kruskal's total weight. Work out what each prints first, then pick.
An adjacency list, with neighbours in the order the edges were added. BFS from 0: what does it print?
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7 int n = 6;8 vector<vector<int>> adj(n);9 auto add = [&](int u, int v) { adj[u].push_back(v); adj[v].push_back(u); };10 add(0, 3); add(0, 1); add(1, 4); add(3, 4); add(3, 2); add(4, 5); add(2, 5);11 vector<bool> seen(n, false);12 queue<int> q;13 seen[0] = true;14 q.push(0);15 while (!q.empty()) {16 int u = q.front();17 q.pop();18 cout << u << " ";19 for (int v : adj[u])20 if (!seen[v]) {21 seen[v] = true;22 q.push(v);23 }24 }25 cout << "\n";26 return 0;27}
The same graph, DFS from 0: what does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5vector<vector<int>> adj(6);6vector<bool> seen(6, false);7 8void dfs(int u) {9 seen[u] = true;10 cout << u << " ";11 for (int v : adj[u])12 if (!seen[v])13 dfs(v);14}15 16int main() {17 auto add = [](int u, int v) { adj[u].push_back(v); adj[v].push_back(u); };18 add(0, 3); add(0, 1); add(1, 4); add(3, 4); add(3, 2); add(4, 5); add(2, 5);19 dfs(0);20 cout << "\n";21 return 0;22}
Directed edges 2→0, 3→0, 3→1, 0→4, 1→4, 4→5: what does Kahn's algorithm print?
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7 int n = 6;8 vector<vector<int>> adj(n);9 vector<int> indeg(n, 0);10 auto add = [&](int u, int v) { adj[u].push_back(v); indeg[v]++; };11 add(2, 0); add(3, 0); add(3, 1); add(0, 4); add(1, 4); add(4, 5);12 queue<int> q;13 for (int v = 0; v < n; v++)14 if (indeg[v] == 0) q.push(v);15 while (!q.empty()) {16 int u = q.front();17 q.pop();18 cout << u << " ";19 for (int v : adj[u])20 if (--indeg[v] == 0)21 q.push(v);22 }23 cout << "\n";24 return 0;25}
Dijkstra from 0 (the priority_queue version): what is dist?
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8typedef pair<int, int> P;9 10int main() {11 int n = 5;12 vector<vector<P>> g(n);13 auto add = [&](int u, int v, int w) { g[u].push_back({v, w}); g[v].push_back({u, w}); };14 add(0, 1, 5); add(0, 2, 1); add(2, 1, 2); add(1, 3, 1);15 add(2, 3, 6); add(3, 4, 2); add(2, 4, 9);16 vector<int> dist(n, 1000000000);17 priority_queue<P, vector<P>, greater<P>> pq;18 dist[0] = 0;19 pq.push({0, 0});20 while (!pq.empty()) {21 int d = pq.top().first, u = pq.top().second;22 pq.pop();23 if (d > dist[u]) continue;24 for (const P& e : g[u])25 if (d + e.second < dist[e.first]) {26 dist[e.first] = d + e.second;27 pq.push({dist[e.first], e.first});28 }29 }30 for (int x : dist) cout << x << " ";31 cout << "\n";32 return 0;33}
Kruskal's minimum spanning tree: what is the total weight?
1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9vector<int> parent(5);10 11int find(int x) {12 if (parent[x] != x) parent[x] = find(parent[x]);13 return parent[x];14}15 16int main() {17 iota(parent.begin(), parent.end(), 0);18 vector<Edge> e = {{0, 1, 2}, {0, 3, 6}, {1, 2, 3}, {1, 3, 8},19 {1, 4, 5}, {2, 4, 7}, {3, 4, 9}};20 sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });21 int total = 0;22 for (const Edge& x : e) {23 int a = find(x.u), b = find(x.v);24 if (a != b) {25 parent[a] = b;26 total += x.w;27 }28 }29 cout << total << "\n";30 return 0;31}