BFS
Breadth-first search visits a graph level by level. A queue holds the frontier. The first time you reach a vertex in an unweighted graph is a shortest path in number of edges.
Detailed Explanation
Start at a source s. Mark it visited and enqueue it. While the queue is not empty, dequeue u and enqueue each unvisited neighbor, marking them as you enqueue. Vertices leave the queue in order of increasing distance from s. That is the whole algorithm.
The queue is essential. A stack would be DFS. In C the queue is a circular buffer of vertex ids, or a linked list. Size it to n if you mark on enqueue: each vertex enters at most once. If you mark on dequeue, the same vertex can sit in the queue several times and you need more space.
visited is essential on a graph. On a tree you can skip it if you never walk the parent edge, but a missed parent check is a cycle of two and an infinite loop. Allocate char visited[n] (or a bitset) and a dist[n] if you want distances. dist[v] = dist[u] + 1 when you first see v from u. A parent[n] array reconstructs the path.
BFS from one source does not visit another component. A full traversal loops over all vertices and starts a BFS from each unmarked one. That is how you count components.
Unweighted shortest path is the headline application. Weighted edges need Dijkstra or Bellman-Ford; BFS will ignore the weights and lie. 0-1 BFS (a deque, 0-weight edges at the front) is the special case that still feels like BFS.
C pitfalls are bounds and ownership. Neighbor indices must be in 0 .. n-1. The queue must not overflow. visited must be reset if you run BFS more than once on the same buffers.
Code Examples
#include <stdio.h>
#include <string.h>
enum { N = 4 };
static int bfs(int adj[N][N], int src, int dst)
{
int q[N];
int head = 0, tail = 0;
int dist[N];
char seen[N];
memset(seen, 0, sizeof seen);
for (int i = 0; i < N; i++) {
dist[i] = -1;
}
q[tail++] = src;
seen[src] = 1;
dist[src] = 0;
while (head < tail) {
int u = q[head++];
if (u == dst) {
return dist[u];
}
for (int v = 0; v < N; v++) {
if (adj[u][v] && !seen[v]) {
seen[v] = 1;
dist[v] = dist[u] + 1;
q[tail++] = v;
}
}
}
return -1;
}
int main(void)
{
int adj[N][N] = {
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
{0, 0, 0, 0},
};
printf("%d\n", bfs(adj, 0, 3)); /* prints: 3 */
return 0;
}Common Gotchas
Forgetting `visited` on a graph with a cycle never finishes
mark when you enqueue.
BFS distance is hops, not weights
a cheap long path will lose to an expensive single edge if you wanted weights.
A queue of size `n` overflows if you allow duplicates
mark on enqueue, or allocate more.
Isolated vertices never appear unless you start from them or iterate all sources
Isolated vertices never appear unless you start from them or iterate all sources