Breadth-first search starts at a source, visits all neighbors, then their neighbors, and so on, using a queue. In an unweighted graph the first time BFS reaches a vertex is along a shortest path in edges, so storing the distance when enqueuing gives shortest hop counts. With an adjacency matrix BFS runs in O(V^2); with lists, O(V + E).
Remember
dist[src] = 0; enqueue(src);
while (queue not empty) {
u = dequeue();
for each neighbor v of u:
if (dist[v] < 0) { dist[v] = dist[u] + 1; enqueue(v); }
}
Reference
Cheat Sheet
Keep these facts handy while you work with Breadth-First Search (BFS) in C in C.
Distances are listed by vertex number: vertex 5 is three edges away.
Edge Cases & Pitfalls
Check these before relying on Breadth-First Search (BFS) in C in real programs.
mark
Marking on dequeue instead of enqueue
This can enqueue a vertex many times. Mark when enqueuing.
size
Queue size
Each vertex enters the queue once, so V entries are enough.
Remember
Key Takeaways
Queue and visited.
Mark when enqueuing.
Shortest paths in unweighted graphs.
One line: Breadth-first search starts at a source, visits all neighbors, then their neighbors, and so on, using a queue.
Frequently Asked Questions
A graph traversal that visits vertices in order of increasing distance from the source, using a queue.
Yes, in unweighted graphs it finds paths with the fewest edges.
Continue with "Depth-First Search (DFS) in C" next. Explore a graph recursively and count connected components. The C Graphs hub lists every topic in order.