Breadth-first search
Breadth-first search (BFS) is an algorithm for traversing or searching through a graph or tree.
It explores all nodes at the current level (or depth) before moving on to the nodes at the next level. BFS is particularly useful for finding the shortest path in an unweighted graph and for visiting every vertex of a graph systematically.
Steps
- Start at a node (often called the root in a tree or any selected node in a graph). 2 .Use a queue to keep track of the nodes to be visited. The queue follows the First-In-First-Out (FIFO) principle, ensuring that nodes are explored level by level.
- Mark the starting node as visited to prevent revisiting it.
- Add all unvisited neighbors of the current node to the queue.
- Dequeue the first node in the queue and explore all its unvisited neighbors.
- Repeat until all nodes at one level are visited before moving to the next level.