BFS
Breadth-first search visits a graph level by level: all nodes at distance 0, then 1, then 2. A queue holds the frontier. On an unweighted graph, the first time you reach a node is a shortest path.
Detailed Explanation
You are finding the fewest hops from a user to another user in a social graph, or the nearest exit in a grid. Depth-first search will wander down one corridor. BFS expands a ring. The queue guarantees that a node popped at step k was first reached in k edges.
The pattern:
- Push the start. Mark it visited (or set
dist[start] = 0). - While the queue is not empty, pop
u. - For each unused neighbour
v, mark visited, recorddist[v] = dist[u] + 1(andparent[v] = uif you need the path), and pushv.
Mark visited when you push, not when you pop. Marking on pop lets the same node sit in the queue many times and explodes the queue on dense graphs.
C++ representation: adjacency list vector<vector<int>>, or a grid with four deltas. The queue is std::queue<int>. Distances are a vector<int> initialised to -1. Reconstruct a path by walking parent back to the start and reversing.
BFS on a tree without a visited set still needs to avoid the parent, or you bounce. BFS on a directed graph only follows outgoing edges. BFS on a weighted graph is not shortest path; use Dijkstra (priority_queue) or 0-1 BFS if weights are 0/1.
Multi-source BFS pushes every source first. The first time a cell is reached is the distance to the nearest source. Flood fill and "nearest zero in a matrix" are this.
Complexity is O(V + E): each node is pushed once, each edge is looked at once. Space is O(V) for the queue and the visited array. A complete binary tree's last level can hold V/2 nodes in the queue.
std::deque is the queue if you need 0-1 BFS (push_front for weight 0, push_back for weight 1). Do not use priority_queue for unweighted BFS; it is slower and unnecessary.
Code Examples
#include <cstddef>
#include <iostream>
#include <queue>
#include <vector>
std::vector<int> bfsDist(const std::vector<std::vector<int>>& g, int start) {
std::vector<int> dist(g.size(), -1);
std::queue<int> q;
dist[static_cast<std::size_t>(start)] = 0;
q.push(start);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : g[static_cast<std::size_t>(u)]) {
if (dist[static_cast<std::size_t>(v)] != -1) continue;
dist[static_cast<std::size_t>(v)] = dist[static_cast<std::size_t>(u)] + 1;
q.push(v);
}
}
return dist;
}
int main() {
std::vector<std::vector<int>> g{{1, 2}, {0, 3}, {0}, {1}};
auto d = bfsDist(g, 0);
std::cout << d[3] << '\n'; // prints: 2
}Common Gotchas
Marking visited on pop
the same node is enqueued through many edges and the queue grows like the number of paths, not the number of nodes.
BFS is not Dijkstra
a cheaper-later edge will not update a neighbour you already marked. Use a heap for positive weights.
Grid bounds
check `nr >= 0 && nr < rows` before you index. A `visited[r][c]` or a sentinel in `dist` prevents revisiting.
Path reconstruction is reversed
walking `parent` from the goal yields the path backwards. `std::reverse` it.