Kodewick
Start learning →
Patterns: graphs34 / 50

Patterns: graphs

Lesson 34 of 50 · Part 6 · Graphs · about 18 minutes

This graph review covers treating a 2D grid as a graph (one vertex per square, DFS to count pieces, BFS for the fewest steps), choosing a shortest-path algorithm by the edge weights, and the hand calculations exams ask for.

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 each square is a vertex, with edges to the squares above, below, left and right (sometimes diagonally too). The edges needn't be stored: two direction arrays, dr and dc, work them out as you go.

  • Counting connected pieces (number of islands, connected regions in an image): scan square by square, and at each land square not yet visited, add 1 and DFS from it to "flood" the whole piece. This is a flood fill.
  • Fewest steps (a maze, a knight's moves): BFS.
  • Spreading from several starts at once (a fire spreading, the distance to the nearest exit): put every start in the queue together, then BFS; this is 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 square by square, and at land DFS to mark the whole island (the picture marks which island with a letter; the code just turns it into 0)
main.c
1#include <stdio.h>2 3#define R 44#define C 55 6int g[R][C] = {7    {1, 1, 0, 0, 1},8    {1, 0, 0, 1, 1},9    {0, 0, 1, 0, 0},10    {1, 0, 1, 1, 0},11};12 13int sink(int r, int c) {           // flood the island at (r, c); returns how many squares it had14    if (r < 0 || r >= R || c < 0 || c >= C || g[r][c] != 1)15        return 0;16    g[r][c] = 0;                   // turned to water, so it's never visited again17    return 1 + sink(r + 1, c) + sink(r - 1, c) + sink(r, c + 1) + sink(r, c - 1);18}19 20int main(void) {21    int count = 0;22    for (int r = 0; r < R; r++)23        for (int c = 0; c < C; c++)24            if (g[r][c] == 1) {25                count++;26                printf("island %d starts at (%d, %d), %d squares\n", count, r, c, sink(r, c));27            }28    printf("%d islands in all\n", count);29    return 0;30}
Output
island 1 starts at (0, 0), 3 squares
island 2 starts at (0, 4), 3 squares
island 3 starts at (2, 2), 3 squares
island 4 starts at (3, 0), 1 squares
4 islands in all

Check "outside the grid" and "not unvisited land" first, then recurse: that way none of the four calls needs its own checks. Turning land into 0 as "visited" saves a visited array (keep a separate one when the problem says the input mustn't change).

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

Finish sink: return if it's outside the grid or not land (g[r][c] != '1'); otherwise turn it into '0' and recurse in all four directions.

It should print
4
exercise1.c
1#include <stdio.h>2 3#define R 54#define C 65 6char g[R][C + 1] = {7    "110010",8    "100011",9    "001000",10    "011001",11    "000011",12};13 14void sink(int r, int c) {15    // outside or not '1': return; otherwise g[r][c] = '0', then sink up, down, left and right16}17 18int main(void) {19    int count = 0;20    for (int r = 0; r < R; r++)21        for (int c = 0; c < C; c++)22            if (g[r][c] == '1') {23                count++;24                sink(r, c);25            }26    printf("%d\n", count);27    return 0;28}
Output
Press Run or Ctrl+Enter
Exercise 2

Rotting oranges

2 is a rotten orange, 1 a fresh one, 0 an empty square. Each minute, rotten oranges rot the fresh ones above, below, left and right of them. Multi-source BFS: every rotten orange goes in the queue together at the start (time 0). Finish 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.c
1#include <stdio.h>2 3#define R 44#define C 45 6int minutes(int g[R][C]) {7    int t[R][C], qr[R * C], qc[R * C], front = 0, rear = 0;8    int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};9    for (int r = 0; r < R; r++)10        for (int c = 0; c < C; c++) {11            t[r][c] = -1;12            if (g[r][c] == 2) {13                t[r][c] = 0;14                qr[rear] = r; qc[rear] = c; rear++;15            }16        }17    while (front < rear) {18        int r = qr[front], c = qc[front];19        front++;20        // four directions: inside the grid, fresh (1), t still -1: t = t[r][c] + 1, queue it21    }22    int most = 0;23    for (int r = 0; r < R; r++)24        for (int c = 0; c < C; c++) {25            if (g[r][c] == 1 && t[r][c] == -1) return -1;26            if (t[r][c] > most) most = t[r][c];27        }28    return most;29}30 31int main(void) {32    int a[R][C] = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}};33    int b[R][C] = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {1, 0, 0, 1}};34    printf("%d\n%d\n", minutes(a), minutes(b));35    return 0;36}
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 (steps, changes)BFSO(n + e)
Weights only 0 and 1deque BFS (0 edges go on the front)O(n + e)
One start, every weight ≥ 0Dijkstra (an array for small n, a heap for sparse graphs)O(n²) or O((n + e) log n)
One start, negative edgesBellman-Ford / SPFAO(n·e)
A directed acyclic graphrelax once in topological orderO(n + e)
Every pair, n only a few hundredFloydO(n³)

Some easy mistakes:

  • Using Dijkstra with negative edges: the counterexample from the Dijkstra lesson gives the wrong answer.
  • Using BFS for shortest paths in a weighted graph: a path with fewer edges isn't necessarily shorter.
  • Putting k on the inside of Floyd's three loops: the k in d[i][j] = min(d[i][j], d[i][k] + d[k][j]) must be outermost. It means "the shortest path when only 0 to k may be used as stops", and the k − 1 case has to be complete first.
  • Running Bellman-Ford on an undirected graph: a single negative edge is a negative cycle (there and back gets shorter every time).
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

Fill in Floyd's three loops: k outermost, and update d[i][j] when d[i][k] + d[k][j] is smaller. (INF is a thousand million, so even 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.c
1#include <stdio.h>2 3#define N 44#define INF 10000000005 6int main(void) {7    int d[N][N];8    for (int i = 0; i < N; i++)9        for (int j = 0; j < N; j++)10            d[i][j] = i == j ? 0 : INF;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: update if d[i][k] + d[k][j] < d[i][j]14    for (int i = 0; i < N; i++) {15        for (int j = 0; j < N; j++)16            printf("%d ", d[i][j]);17        printf("\n");18    }19    return 0;20}
Output
Press Run or Ctrl+Enter

Pattern 3: exam hand calculations

Exam graph questions are mostly "write out the algorithm's working step by step". A few fixed formats:

The Dijkstra table: one row per round, with the current dist of every unsettled vertex, and the smallest circled (that round settles it); the next row relaxes with it. Using 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      

Dijkstra worked by hand: each row is a round, the highlighted box is the vertex settled that round; once settled, its column gets "–"

Prim's and Kruskal's order: for Prim, write "from v, the edges added in turn", each step taking the shortest edge with one end in the tree and one out; for Kruskal, write "by weight, smallest first: take, skip, take…", saying for each skip which edges it would make a cycle with.

All topological orders: at each step try every vertex whose in-degree is 0 now, and draw it as a tree; the number of leaves is the number of orders. This program lists them all by backtracking:

main.c
1#include <stdio.h>2 3#define N 54 5int a[N][N], indeg[N], used[N], order[N], count = 0;6 7void all(int k) {                       // k already placed8    if (k == N) {9        count++;10        for (int i = 0; i < N; i++) printf("%d ", order[i]);11        printf("\n");12        return;13    }14    for (int v = 0; v < N; v++)15        if (!used[v] && indeg[v] == 0) {    // try every vertex with in-degree 016            used[v] = 1;17            order[k] = v;18            for (int j = 0; j < N; j++) indeg[j] -= a[v][j];19            all(k + 1);20            for (int j = 0; j < N; j++) indeg[j] += a[v][j];   // undo, try the next21            used[v] = 0;22        }23}24 25int main(void) {26    a[0][2] = a[1][2] = a[2][3] = a[2][4] = 1;   // 0 and 1 before 2, 2 before 3 and 427    for (int u = 0; u < N; u++)28        for (int v = 0; v < N; v++)29            indeg[v] += a[u][v];30    all(0);31    printf("%d in all\n", count);32    return 0;33}
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 question asksAnswer
The sum of all degrees in an undirected graph2e
The sums of in-degrees and of out-degrees in a directed graphboth e
Edges in a complete undirected graph on n verticesn(n − 1) / 2 (complete directed graph n(n − 1))
The fewest edges in a connected graph on n verticesn − 1 (a spanning tree)
The fewest edges on n vertices that guarantee it's connected(n − 1)(n − 2) / 2 + 1
The number of 1s in the adjacency matrixundirected 2e, directed e
The number of edge nodes in the adjacency listundirected 2e, directed e
Trees in a forest with n vertices and e edgesn − e

The idea behind "guarantee it's connected": first join n − 1 vertices every way possible, using (n − 1)(n − 2) / 2 edges, and the last vertex is still on its own; 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: direction arrays give the neighbours; flood with DFS to count pieces, BFS for fewest steps
  • Spreading from several starts: queue them all first, then BFS
  • Shortest paths, weights first: unweighted BFS, non-negative Dijkstra, negative Bellman-Ford, every pair Floyd
  • Exams: Dijkstra's table settles one per round; degrees sum to 2e; connected for sure 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 && …) …5}

Chapter 5 quick check

5 questions: BFS and DFS on the same graph, the order Kahn gives, Dijkstra's distances, and a minimum spanning tree's total. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

BFS from 0 (adjacency matrix, neighbours smallest first). What does it print?

1#include <stdio.h>2 3#define N 64 5int a[N][N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9int main(void) {10    add(0, 3); add(0, 1); add(1, 4); add(3, 4); add(3, 2); add(4, 5); add(2, 5);11    int seen[N] = {0}, q[N], front = 0, rear = 0;12    seen[0] = 1;13    q[rear++] = 0;14    while (front < rear) {15        int u = q[front++];16        printf("%d ", u);17        for (int v = 0; v < N; v++)18            if (a[u][v] && !seen[v]) {19                seen[v] = 1;20                q[rear++] = v;21            }22    }23    printf("\n");24    return 0;25}
Guess the outputA wrong guess is fine

The same graph, DFS from 0. What does it print?

1#include <stdio.h>2 3#define N 64 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9void dfs(int u) {10    seen[u] = 1;11    printf("%d ", u);12    for (int v = 0; v < N; v++)13        if (a[u][v] && !seen[v])14            dfs(v);15}16 17int main(void) {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    printf("\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 <stdio.h>2 3#define N 64 5int a[N][N];6 7int main(void) {8    a[2][0] = a[3][0] = a[3][1] = a[0][4] = a[1][4] = a[4][5] = 1;9    int indeg[N] = {0}, q[N], front = 0, rear = 0;10    for (int u = 0; u < N; u++)11        for (int v = 0; v < N; v++)12            indeg[v] += a[u][v];13    for (int v = 0; v < N; v++)14        if (indeg[v] == 0) q[rear++] = v;15    while (front < rear) {16        int u = q[front++];17        printf("%d ", u);18        for (int v = 0; v < N; v++)19            if (a[u][v] && --indeg[v] == 0)20                q[rear++] = v;21    }22    printf("\n");23    return 0;24}
Guess the outputA wrong guess is fine

Dijkstra from 0. What is dist?

1#include <stdio.h>2 3#define N 54#define INF 10000000005 6int w[N][N], dist[N], done[N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10int main(void) {11    for (int i = 0; i < N; i++)12        for (int j = 0; j < N; j++)13            w[i][j] = INF;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    for (int i = 0; i < N; i++) dist[i] = INF;17    dist[0] = 0;18    for (int k = 0; k < N; k++) {19        int u = -1;20        for (int i = 0; i < N; i++)21            if (!done[i] && (u == -1 || dist[i] < dist[u])) u = i;22        done[u] = 1;23        for (int v = 0; v < N; v++)24            if (!done[v] && w[u][v] != INF && dist[u] + w[u][v] < dist[v])25                dist[v] = dist[u] + w[u][v];26    }27    for (int i = 0; i < N; i++) printf("%d ", dist[i]);28    printf("\n");29    return 0;30}
Guess the outputA wrong guess is fine

Prim from 0. What's the minimum spanning tree's total weight?

1#include <stdio.h>2 3#define N 54#define INF 10000000005 6int w[N][N];7 8void add(int u, int v, int c) { w[u][v] = w[v][u] = c; }9 10int main(void) {11    for (int i = 0; i < N; i++)12        for (int j = 0; j < N; j++)13            w[i][j] = INF;14    add(0, 1, 2); add(0, 3, 6); add(1, 2, 3); add(1, 3, 8);15    add(1, 4, 5); add(2, 4, 7); add(3, 4, 9);16    int in[N] = {0}, low[N], total = 0;17    in[0] = 1;18    for (int i = 0; i < N; i++) low[i] = w[0][i];19    for (int k = 1; k < N; k++) {20        int v = -1;21        for (int i = 0; i < N; i++)22            if (!in[i] && (v == -1 || low[i] < low[v])) v = i;23        in[v] = 1;24        total += low[v];25        for (int j = 0; j < N; j++)26            if (!in[j] && w[v][j] < low[j]) low[j] = w[v][j];27    }28    printf("%d\n", total);29    return 0;30}