Kodewick
Start learning →
Patterns: graphs36 / 52

Patterns: graphs

Lesson 36 of 52 · Part 6 · Graphs · about 18 minutes

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.
01234011001110011200100310110

Number of islands: 1 is land, 0 is water, and land joined up, down, left or right is one island. Scan the cells; at land, DFS to mark the whole island (the picture marks which island with a letter; the code just turns it into 0)
main.cpp
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}
Output
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.

Choose one

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
Exercise 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.

It should print
4
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter
Exercise 2

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.

It should print
6
-1
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

Pattern 2: shortest paths, look at the weights first

What the problem looks likeUseTime
No weights, or every edge the same length (how many steps, how many changes)BFS, queueO(n + e)
Weights only 0 and 10-1 BFS: a deque, push_front for 0 edges, push_back for 1 edgesO(n + e)
One source, all weights ≥ 0Dijkstra (an array when n is small, priority_queue for a sparse graph)O(n²) or O((n + e) log n)
One source, negative edgesBellman-Ford / SPFAO(n·e)
A directed acyclic graphrelax once in topological orderO(n + e)
All pairs, n only a few hundredFloydO(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 greater in the priority_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 + w overflows 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).
Choose one

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?

Exercise 3

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.)

It should print
0 5 8 9 
6 0 3 4 
3 5 0 1 
2 4 7 0 
exercise3.cpp
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}
Output
Press Run or Ctrl+Enter

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:

12345settledround 1      round 2      round 3      round 4      round 5      

The Dijkstra table by hand: one row per round, the lit cell is the vertex settled that round; once settled, its column gets "–"

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:

main.cpp
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}
Output
0 1 2 3 4 
0 1 2 4 3 
1 0 2 3 4 
1 0 2 4 3 
4 in all
Choose one

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 questionThe answer
Sum of all degrees in an undirected graph2e
Sum of in-degrees, sum of out-degrees in a directed graphboth e
Edges in a complete undirected graph on n verticesn(n − 1) / 2 (complete directed: n(n − 1))
Fewest edges in a connected graph on n verticesn − 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 matrixundirected 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 edgesn − 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.

Choose one

An undirected graph on 7 vertices (no repeated edges): at least how many edges guarantee it's connected, however they're placed?

Choose one

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?

Summary

Take-away

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.

Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}