Breadth-first search (BFS) in C, visualized step by step
Starting from one vertex, visit everything one step away first, then two steps away, ring by ring. A queue does it: first in, first out; mark a vertex as seen when it enters, so it never enters twice.
bfs.c
#include <stdio.h>
#define N 6
int main(void) {
int adj[N][N] = {
{0, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 1, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0},
};
int seen[N] = {0};
int queue[N], head = 0, tail = 0;
seen[0] = 1;
queue[tail++] = 0;
while (head < tail) {
int v = queue[head++];
printf("%d ", v);
for (int w = 0; w < N; w++) {
if (adj[v][w] && !seen[w]) {
seen[w] = 1;
queue[tail++] = w;
}
}
}
printf("\n");
return 0;
}
How Breadth-first search (BFS) works
- Mark the start as seen and put it in the queue.
- Take the vertex v at the front of the queue and record it.
- For each neighbour of v not seen yet: mark it and add it to the back.
- When the queue is empty, every reachable vertex has been visited.
What to watch
The queueOut on the left, in on the right: vertices of the same level sit together.
seenMarked on entering the queue, so no vertex is queued twice.
FAQ
What is the time complexity of BFS?
O(V + E): each vertex is queued and taken out once, and each edge is looked at once.
BFS vs DFS?
BFS uses a queue and spreads out level by level: it finds the fewest steps (shortest paths in an unweighted graph). DFS uses a stack or recursion and goes deep first: good for components and backtracking.
Why mark a vertex when it is queued, not when it is taken out?
Marking it later lets several neighbours queue the same vertex, doing the same work many times.