Breadth-First Search (BFS) logic
What you'll learn: How to explore a graph level-by-level using a queue to find the shortest path in an unweighted network.
The "Ripples in a Pond" approach
Imagine dropping a stone into a still pond. The water doesn't shoot out in one long line; instead, it creates a circular ripple that expands outward. Breadth-First Search (BFS) works exactly like that ripple.
If you are at a starting node (let's call it Node A), BFS visits all of Node A's immediate neighbors first. Only after it has finished visiting every direct neighbor does it move out to the "friends of friends." This ensures that you explore the graph in layers. Because of this layered approach, the first time you reach a target node, you are guaranteed to have found the shortest path possible in terms of the number of edges.
The Queue: Your "To-Do" List
To keep track of who to visit next without getting lost, BFS uses a Queue (First-In, First-Out). The logic follows three repeating steps:
- Visit a node and mark it so you don't visit it twice.
- Enqueue all of its unvisited neighbors.
- Dequeue the next node from the front of the line and repeat.
BFS in Logic
Here is how we represent this logic in C. We assume we have an adjacency matrix graph[V][V] and a simple queue array.
#include <stdio.h>
#include <stdbool.h>
#define V 5 // Number of vertices
void bfs(int graph[V][V], int startNode) {
bool visited[V] = {false};
int queue[V];
int front = 0, rear = 0;
// Start with the initial node
visited[startNode] = true;
queue[rear++] = startNode;
while (front < rear) {
// Pull the next node to explore
int current = queue[front++];
printf("Visited node: %d\n", current);
// Check all possible neighbors
for (int neighbor = 0; neighbor < V; neighbor++) {
// If there's an edge and we haven't been there yet
if (graph[current][neighbor] == 1 && !visited[neighbor]) {
visited[neighbor] = true;
queue[rear++] = neighbor; // Add to "to-do" list
}
}
}
}
Why use it?
BFS is the gold standard when you need the "closest" result. For example, in a social network, BFS finds your "1st-degree" connections before looking at "2nd-degree" connections. In a GPS navigation app, BFS helps find the path with the fewest number of turns or hops between intersections.
Key takeaway
BFS explores a graph layer-by-layer using a queue to ensure it visits all immediate neighbors before moving further away.