39. Breadth First Search (BFS)
BFS is a graph traversal algorithm that explores all the neighbor nodes at the current depth level before moving on to the nodes at the next depth level.
Concept: Exploring Layers
Imagine ripples in a pond. BFS explores layer by layer, finding all nodes one step away, then all nodes two steps away, and so on.
BFS uses a Queue to keep track of nodes to visit next, ensuring a level-by-level exploration.
Algorithm Steps
- Start at source node S, mark as visited, and enqueue it.
- While the queue is not empty:
- Dequeue a node
U. - For every unvisited neighbor
VofU:- Mark
Vas visited and enqueueV.
- Mark
- Dequeue a node
Use Cases
- Finding the shortest path in an unweighted graph (since it explores closest nodes first).
- Web crawlers (crawling level by level).