Breadth-first search (BFS)
Breadth-first search (BFS) spreads out from a start vertex level by level with a queue, so in an unweighted graph the step count when a vertex is first reached is its shortest distance; C++ uses std::queue and marks vertices when pushed.
A social app says "you and this person are 3 friends apart", a metro app works out "the fewest changes", a maze game asks for "the fewest moves": all the same problem. In a graph where every edge has the same length, what is the smallest number of edges from the start to each other vertex? The answer is a plain idea: find every vertex 1 step from the start, then from those the ones 2 steps away, then 3… spreading out in rings like ripples on water. This is breadth-first search (BFS).
A queue, level by level
"Near ones first, far ones later" is exactly first-in, first-out, a queue:
- Put the start in the queue and mark it "seen".
- While the queue isn't empty: take the front vertex u; for each neighbour v of u that is not seen yet, mark it and queue it.
Anything queued earlier is no farther from the start than anything queued later, so the order vertices come out is level by level.
queue
Every vertex goes into the queue and out of it once. With an adjacency list each vertex's neighbours are looked at once too, 2e neighbours in all, so BFS is O(n + e); with an adjacency matrix, finding neighbours means scanning a whole row, so it is 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 is 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 none of them saw it. So dist[v] = dist[u] + 1 is right the first time and never changes.
Add from[v] = u to record "where v was found from", and walking back from the end along from gives a shortest path. (Don't call it prev: after using namespace std; a global prev clashes with std::prev and the program doesn't compile.)
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 6;6 7int a[N][N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11int dist[N], from[N];12 13void bfs(int s) {14 for (int i = 0; i < N; i++) dist[i] = -1; // -1: not seen yet15 dist[s] = 0;16 from[s] = -1;17 queue<int> q;18 q.push(s);19 cout << "order out: ";20 while (!q.empty()) {21 int u = q.front();22 q.pop();23 cout << u << ' ';24 for (int v = 0; v < N; v++)25 if (a[u][v] && dist[v] == -1) { // an edge, and not seen yet26 dist[v] = dist[u] + 1; // mark it when it goes in27 from[v] = u;28 q.push(v);29 }30 }31 cout << '\n';32}33 34void path(int v) { // print what comes before, then yourself35 if (from[v] != -1) {36 path(from[v]);37 cout << " -> ";38 }39 cout << v;40}41 42int main() {43 add(0, 2); add(0, 4); add(2, 1); add(2, 3);44 add(4, 3); add(1, 5); add(3, 5);45 bfs(0);46 for (int i = 0; i < N; i++)47 cout << "dist[" << i << "] = " << dist[i] << '\n';48 cout << "shortest path to 5: ";49 path(5);50 cout << '\n';51 return 0;52}
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 there's no separate visited array. Note that q.pop() returns nothing: read the front with q.front() first, then throw it away with pop().
This holds only for unweighted graphs (or all edges the same length). When edges differ in length, fewer steps doesn't mean a shorter path; that's Dijkstra, 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
✓Fill in the BFS while loop: u has just come out of the queue; for each neighbour v that is joined to u and not seen yet (dist[v] == -1), set its dist and queue it.
0 1 1 2 3 4 2
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 7;6 7int a[N][N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11int main() {12 add(0, 1); add(0, 2); add(1, 3); add(2, 3);13 add(3, 4); add(4, 5); add(2, 6);14 int dist[N];15 for (int i = 0; i < N; i++) dist[i] = -1;16 queue<int> q;17 dist[0] = 0;18 q.push(0);19 while (!q.empty()) {20 int u = q.front();21 q.pop();22 // for each v: if a[u][v] and dist[v] == -1, set dist[v] = dist[u] + 1 and queue v23 }24 for (int i = 0; i < N; i++)25 cout << dist[i] << ' ';26 cout << '\n';27 return 0;28}
What marking too late does
A common mistake: marking a vertex "seen" only when it comes out of the queue. It looks right, but before a vertex comes out, several neighbours may see it, and since it isn't marked, each of them queues it again. In the graph of the first two steps, 3 would be queued once by 2 and once by 4. In a graph with many edges it gets far worse:
1#include <iostream>2#include <queue>3using namespace std;4 5const int N = 100;6 7int a[N][N], seen[N];8 9int early() { // mark when it goes in10 int pushes = 0;11 for (int i = 0; i < N; i++) seen[i] = 0;12 queue<int> q;13 seen[0] = 1;14 q.push(0); pushes++;15 while (!q.empty()) {16 int u = q.front();17 q.pop();18 for (int v = 0; v < N; v++)19 if (a[u][v] && !seen[v]) {20 seen[v] = 1;21 q.push(v); pushes++;22 }23 }24 return pushes;25}26 27int late() { // mark only when it comes out28 int pushes = 0;29 for (int i = 0; i < N; i++) seen[i] = 0;30 queue<int> q;31 q.push(0); pushes++;32 while (!q.empty()) {33 int u = q.front();34 q.pop();35 if (seen[u]) continue;36 seen[u] = 1;37 for (int v = 0; v < N; v++)38 if (a[u][v] && !seen[v]) {39 q.push(v); pushes++;40 }41 }42 return pushes;43}44 45int main() {46 for (int i = 0; i < N; i++) // 100 vertices, every pair joined47 for (int j = 0; j < N; j++)48 a[i][j] = i != j;49 cout << "mark on the way in: queued " << early() << " times\n";50 cout << "mark on the way out: queued " << late() << " times\n";51 return 0;52}
mark on the way in: queued 100 times mark on the way out: queued 4951 times
100 vertices, every pair joined: the right version queues each vertex once. Marking late, 0 comes out and queues all 99 others, 1 comes out and queues the 98 still unmarked… and the queue grows to nearly five thousand. Skipping seen vertices on the way out keeps the answer right, but time and space are no longer O(n + e), and dist is easier to get wrong. One rule: mark a vertex when it goes into the queue.
BFS from 0 on a graph stored as a vector<vector<int>>. What does it print?
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7 vector<vector<int>> adj(5);8 auto add = [&](int u, int v) {9 adj[u].push_back(v);10 adj[v].push_back(u);11 };12 add(0, 3); add(0, 1); add(2, 4); add(0, 2); add(1, 4);13 vector<int> seen(5, 0);14 queue<int> q;15 seen[0] = 1;16 q.push(0);17 while (!q.empty()) {18 int u = q.front();19 q.pop();20 cout << u << ' ';21 for (int v : adj[u])22 if (!seen[v]) {23 seen[v] = 1;24 q.push(v);25 }26 }27 cout << '\n';28 return 0;29}
| BFS | |
|---|---|
| Uses | a queue |
| Mark when | it goes in |
| Time | adjacency list O(n + e), adjacency matrix O(n²) |
| Space | O(n): the queue, dist |
| Finds | shortest paths (in steps) in unweighted graphs, level-by-level work, connectivity |
A favourite exam question: given a graph's adjacency matrix or adjacency list, write the BFS order from a given vertex. With a matrix, neighbours go in increasing order and the answer is unique; with a list, they go in the order the list stores them. Given only the drawing and no storage, the BFS order isn't unique. The "BFS spanning tree" is the tree the from links make, and its height is how many steps away the farthest vertex is.
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 <iostream>2#include <queue>3using namespace std;4 5const int N = 6;6 7int a[N][N], seen[N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11int main() {12 add(0, 2); add(0, 4); add(2, 1); add(2, 3);13 add(4, 3); add(1, 5); add(3, 5);14 queue<int> q;15 int pushes = 0;16 q.push(0); pushes++;17 while (!q.empty()) {18 int u = q.front();19 q.pop();20 if (seen[u]) continue;21 seen[u] = 1;22 for (int v = 0; v < N; v++)23 if (a[u][v] && !seen[v]) {24 q.push(v); pushes++;25 }26 }27 cout << pushes << "\n";28 return 0;29}
With the STL
Everyday BFS uses two STL pieces: the adjacency list vector<vector<int>> and the queue queue<int>. Wrapped in a function that returns dist:
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6vector<int> bfs(const vector<vector<int>>& adj, int s) {7 vector<int> dist(adj.size(), -1); // -1: not seen yet8 queue<int> q;9 dist[s] = 0;10 q.push(s);11 while (!q.empty()) {12 int u = q.front();13 q.pop();14 for (int v : adj[u]) // only the neighbours that exist15 if (dist[v] == -1) {16 dist[v] = dist[u] + 1;17 q.push(v);18 }19 }20 return dist;21}22 23int main() {24 int n = 7; // vertex 6 is joined to nothing25 int edges[7][2] = {{0, 2}, {0, 4}, {2, 1}, {2, 3}, {4, 3}, {1, 5}, {3, 5}};26 vector<vector<int>> adj(n);27 for (auto& e : edges) {28 adj[e[0]].push_back(e[1]);29 adj[e[1]].push_back(e[0]);30 }31 vector<int> dist = bfs(adj, 0);32 for (int i = 0; i < n; i++)33 cout << "dist[" << i << "] = " << dist[i] << '\n';34 return 0;35}
dist[0] = 0 dist[1] = 2 dist[2] = 1 dist[3] = 2 dist[4] = 1 dist[5] = 3 dist[6] = -1
Vertex 6 can't be reached, so its dist stays -1: BFS also tells you what is connected to the start. adj is passed as const &, so the graph isn't copied.
What's inside: queue<int> isn't a new structure but an adaptor. By default it wraps a deque<int> and lets you in only at the back and out only at the front: push is push_back, pop is pop_front. A deque is an array of blocks, O(1) at both ends, with none of the index arithmetic a hand-made circular queue needs.
| Operation | Code | Cost |
|---|---|---|
| Enqueue | q.push(v) | O(1) |
| Look at the front | q.front() | O(1) |
| Dequeue | q.pop() (returns nothing) | O(1) |
| Empty? | q.empty() | O(1) |
| Queue a grid cell | queue<pair<int, int>>, q.push({r, c}) | O(1) |
In interviews: "fewest steps", "fewest transformations", "how far to the nearest X": whenever every step costs the same, it's BFS. To work level by level (printing a binary tree by levels, finding the depth), start each round of the while loop with int k = q.size(); and take out exactly k: that's one whole level. With several starts ("how far is each cell from the nearest exit") queue all of them at the beginning with dist 0: multi-source BFS.
Fewest steps through a maze
✓In the maze . is open and # is a wall; each step moves one cell up, down, left or right. Find the fewest steps from the top-left corner (0, 0) to the bottom-right corner (4, 5). Each cell is a vertex with edges to the open cells around it; the queue holds pair<int, int> (row, column). Fill in the part of the while loop that looks in the four directions.
13
1#include <iostream>2#include <vector>3#include <string>4#include <queue>5#include <utility>6using namespace std;7 8int main() {9 vector<string> g = {10 "..#...",11 ".##.#.",12 "....#.",13 "#.##..",14 "...#..",15 };16 int R = g.size(), C = g[0].size();17 vector<vector<int>> dist(R, vector<int>(C, -1));18 int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};19 queue<pair<int, int>> q;20 dist[0][0] = 0;21 q.push({0, 0});22 while (!q.empty()) {23 int r = q.front().first, c = q.front().second;24 q.pop();25 // four directions: nr = r + dr[k], nc = c + dc[k];26 // inside the grid, not a wall, dist still -1: set dist, queue it27 }28 cout << dist[R - 1][C - 1] << '\n';29 return 0;30}
A grid has several exits, and you need how many steps each cell is from its nearest exit. With a single BFS, how do you start?
Summary
BFS: a queue, out level by level
- Queue the start; take out u, mark and queue each unseen neighbour
- Mark on the way in, or the same vertex gets queued many times
- dist[v] = dist[u] + 1 when first seen is the shortest path in an unweighted graph
- Adjacency list O(n + e), matrix O(n²); queue's pop returns nothing
1while (!q.empty()) {2 int u = q.front(); q.pop();3 for (int v : adj[u])4 if (dist[v] == -1) dist[v] = dist[u] + 1, q.push(v);5}