Breadth-first search (BFS)
Breadth-first search (BFS) uses a queue to visit a graph level by level, first the vertices 1 edge from the start, then 2, then 3; in an unweighted graph it finds shortest paths as it goes, with dist[v] = dist[u] + 1.
A social app says "you and this person are 3 friends apart", a metro app works out "the fewest changes", a maze game wants "the fewest moves": they're all the same question. In a graph where every edge is the same length, how few edges does it take to get from the start to each vertex? The answer is a plain idea: find every vertex 1 step from the start, then from those every vertex 2 steps away, then 3… spreading out ring by ring like ripples. It's called breadth-first search (BFS).
A queue, level by level
"Deal with the near ones before the far ones" is exactly a queue's first in, first out:
- Put the start in the queue and mark it seen.
- While the queue isn't empty: take out a vertex u; for each neighbour v of u that hasn't been seen, mark it and put it in the queue.
Anything that went in earlier is no farther from the start than anything that went in later, so the order they come out is level by level.
queue
Each vertex goes in and comes out of the queue once. With an adjacency list each vertex's chain is walked once too, and the chains add up to 2e, so BFS is O(n + e); with an adjacency matrix, finding neighbours scans a whole row, so it's O(n²).
An undirected graph has the edges A–C, A–E, C–B, C–D, E–F, B–F, and neighbours are looked at in alphabetical order. In what order does BFS from A visit the vertices?
A graph with n vertices is stored as an adjacency matrix. How long does BFS take?
Shortest paths for free
When a vertex is first seen, it was reached from some u that is d steps from the start, so it is d + 1 steps away. It can't be fewer: every vertex nearer the start came out of the queue earlier and didn't reach it. So dist[v] = dist[u] + 1 is right the first time and never changes.
Keep prev[v] = u as well, "v was found from u", and walking back from the end along prev gives a shortest path.
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 dist[N], prev[N];10 11void bfs(int s) {12 int q[N], front = 0, rear = 0;13 for (int i = 0; i < N; i++) dist[i] = -1; // -1: not seen yet14 dist[s] = 0;15 prev[s] = -1;16 q[rear++] = s;17 printf("order out: ");18 while (front < rear) {19 int u = q[front++];20 printf("%d ", u);21 for (int v = 0; v < N; v++)22 if (a[u][v] && dist[v] == -1) { // an edge, and not seen yet23 dist[v] = dist[u] + 1; // marked as it goes in24 prev[v] = u;25 q[rear++] = v;26 }27 }28 printf("\n");29}30 31void path(int v) { // print the ones before, then this one32 if (prev[v] != -1) {33 path(prev[v]);34 printf(" -> ");35 }36 printf("%d", v);37}38 39int main(void) {40 add(0, 2); add(0, 4); add(2, 1); add(2, 3);41 add(4, 3); add(1, 5); add(3, 5);42 bfs(0);43 for (int i = 0; i < N; i++)44 printf("dist[%d] = %d\n", i, dist[i]);45 printf("shortest path to 5: ");46 path(5);47 printf("\n");48 return 0;49}
order out: 0 2 4 1 3 5 dist[0] = 0 dist[1] = 2 dist[2] = 1 dist[3] = 2 dist[4] = 1 dist[5] = 3 shortest path to 5: 0 -> 2 -> 1 -> 5
dist does two jobs: -1 means not seen, anything else is the number of steps, so no separate visited array is needed. A plain array is enough for the queue, since each vertex goes in at most once and N places can't run out.
This holds only for unweighted graphs (or ones with all edges the same length). When edges differ in length, fewer steps doesn't mean a shorter route, and you need Dijkstra, coming up later.
When is the dist BFS gives a vertex, the first time it sees it, sure to be the shortest path to it?
An undirected graph has the edges A–C, A–E, C–B, C–D, E–F, B–F. BFS starts from A. What is dist[F]?
Every vertex's distance
✓Finish BFS's while loop: u is already out of the queue; look at every neighbour v, and if there's an edge and v hasn't been seen (dist[v] == -1), work out its dist and queue it.
0 1 1 2 3 4 2
1#include <stdio.h>2 3#define N 74 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, 1); add(0, 2); add(1, 3); add(2, 3);11 add(3, 4); add(4, 5); add(2, 6);12 int dist[N], q[N], front = 0, rear = 0;13 for (int i = 0; i < N; i++) dist[i] = -1;14 dist[0] = 0;15 q[rear++] = 0;16 while (front < rear) {17 int u = q[front++];18 // for each v: if a[u][v] and dist[v] == -1, dist[v] = dist[u] + 1, then queue it19 }20 for (int i = 0; i < N; i++)21 printf("%d ", dist[i]);22 printf("\n");23 return 0;24}
Fewest steps through a maze
✓In the maze, . is open and # is a wall; each step moves one square up, down, left or right. Find the fewest steps from the top left (0, 0) to the bottom right (4, 5). Each square is a vertex, with edges to the open squares above, below, left and right of it. Finish the part of the while loop that looks in the four directions.
13
1#include <stdio.h>2 3#define R 54#define C 65 6char g[R][C + 1] = {7 "..#...",8 ".##.#.",9 "....#.",10 "#.##..",11 "...#..",12};13 14int main(void) {15 int dist[R][C], qr[R * C], qc[R * C], front = 0, rear = 0;16 int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};17 for (int i = 0; i < R; i++)18 for (int j = 0; j < C; j++)19 dist[i][j] = -1;20 dist[0][0] = 0;21 qr[rear] = 0; qc[rear] = 0; rear++;22 while (front < rear) {23 int r = qr[front], c = qc[front];24 front++;25 // four directions: nr = r + dr[k], nc = c + dc[k];26 // inside the maze, not a wall, dist still -1: set dist, queue it27 }28 printf("%d\n", dist[R - 1][C - 1]);29 return 0;30}
What marking too late does
A common mistake: marking a vertex "seen" only when it comes out of the queue. It looks fine, but before it comes out a vertex may be spotted by several neighbours, none of which marks it, so it goes into the queue several times. In the 6-vertex graph from the first section, 3 would be queued once by 2 and once by 4. With lots of edges it gets much worse:
1#include <stdio.h>2 3#define N 1004 5int a[N][N], seen[N], q[N * N];6 7int right(void) { // marked as it goes in8 int front = 0, rear = 0, pushes = 0;9 for (int i = 0; i < N; i++) seen[i] = 0;10 seen[0] = 1;11 q[rear++] = 0; pushes++;12 while (front < rear) {13 int u = q[front++];14 for (int v = 0; v < N; v++)15 if (a[u][v] && !seen[v]) {16 seen[v] = 1;17 q[rear++] = v; pushes++;18 }19 }20 return pushes;21}22 23int late(void) { // marked only as it comes out24 int front = 0, rear = 0, pushes = 0;25 for (int i = 0; i < N; i++) seen[i] = 0;26 q[rear++] = 0; pushes++;27 while (front < rear) {28 int u = q[front++];29 if (seen[u]) continue;30 seen[u] = 1;31 for (int v = 0; v < N; v++)32 if (a[u][v] && !seen[v]) {33 q[rear++] = v; pushes++;34 }35 }36 return pushes;37}38 39int main(void) {40 for (int i = 0; i < N; i++) // 100 vertices, every pair joined41 for (int j = 0; j < N; j++)42 a[i][j] = i != j;43 printf("marked going in: queued %d times\n", right());44 printf("marked coming out: queued %d times\n", late());45 return 0;46}
marked going in: queued 100 times marked coming out: queued 4951 times
With 100 vertices all joined to each other, the right version queues each vertex once. Marking late, 0 comes out and queues all 99 others, then 1 comes out and queues the 98 still unmarked… and the queue grows to nearly five thousand. Skipping seen vertices as they come out keeps the answer right, but time and space are no longer O(n + e), and dist is easier to get wrong. There's one rule: mark it as it goes in.
BFS from 0 on a graph stored as an adjacency list (inserting at the front). What does it print?
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int v;6 struct Node *next;7} Node;8 9Node *head[5];10 11void push(int u, int v) {12 Node *p = malloc(sizeof(Node));13 p->v = v;14 p->next = head[u];15 head[u] = p;16}17 18void add(int u, int v) { push(u, v); push(v, u); }19 20int main(void) {21 add(0, 1); add(0, 2); add(0, 3); add(1, 4); add(2, 4);22 int seen[5] = {0}, q[5], front = 0, rear = 0;23 seen[0] = 1;24 q[rear++] = 0;25 while (front < rear) {26 int u = q[front++];27 printf("%d ", u);28 for (Node *p = head[u]; p; p = p->next)29 if (!seen[p->v]) {30 seen[p->v] = 1;31 q[rear++] = p->v;32 }33 }34 printf("\n");35 return 0;36}
| BFS | |
|---|---|
| Uses | a queue |
| Mark when | going in |
| Time | adjacency list O(n + e), adjacency matrix O(n²) |
| Space | O(n): the queue, dist |
| Finds | shortest paths (steps) in unweighted graphs, levels, connectivity |
In exams: given a graph's adjacency matrix or adjacency list, write the BFS order from some vertex. With a matrix the neighbours go in increasing order and the answer is unique; with a list they go in chain order, whatever order the question's chains are in. Given just a picture of the graph with no storage, the BFS order isn't unique. There's also the "BFS spanning tree": the tree that prev joins up, whose height is how many steps the farthest vertex is from the start.
Marking only when a vertex comes out of the queue (the wrong way): on this graph of 6 vertices and 7 edges, how many times does something go into the queue?
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 9int main(void) {10 add(0, 2); add(0, 4); add(2, 1); add(2, 3);11 add(4, 3); add(1, 5); add(3, 5);12 int q[N * N], front = 0, rear = 0, pushes = 0;13 q[rear++] = 0; pushes++;14 while (front < rear) {15 int u = q[front++];16 if (seen[u]) continue;17 seen[u] = 1;18 for (int v = 0; v < N; v++)19 if (a[u][v] && !seen[v]) {20 q[rear++] = v; pushes++;21 }22 }23 printf("%d\n", pushes);24 return 0;25}
Summary
BFS: a queue, out level by level
- Start goes in; take out u, mark and queue its unseen neighbours
- Mark on the way in, or a vertex gets queued several times
- First seen: dist[v] = dist[u] + 1, the shortest path in an unweighted graph
- Adjacency list O(n + e), adjacency matrix O(n²)
1while (front < rear) {2 int u = q[front++];3 for (int v = 0; v < N; v++)4 if (a[u][v] && dist[v] == -1)5 dist[v] = dist[u] + 1, q[rear++] = v;6}