Open In App

What is the alorithm BFS?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The BFS algorithm stands for Breadth-First Search. It is a fundamental algorithm used in graph theory and computer science to traverse or search a graph or tree data structure. The algorithm starts at a designated root node (or start node) and explores all of its neighbors at the present depth level before moving on to the nodes at the next depth level.

Here’s how BFS works:

  1. Start with a queue data structure and enqueue the starting node.
  2. Mark the starting node as visited.
  3. While the queue is not empty:
    • Dequeue a node from the queue.
    • Visit the dequeued node.
    • Enqueue all adjacent nodes of the dequeued node that have not been visited yet.
    • Mark the visited nodes.
  4. Repeat until the queue is empty.

BFS guarantees that it visits all nodes at a given depth level before moving to the nodes at the next depth level. It’s often used to find the shortest path between two nodes in an unweighted graph or to traverse trees level by level.

One of the primary advantages of BFS is its simplicity and the fact that it ensures the shortest path to any reachable node from the starting point in an unweighted graph. However, it requires more memory compared to Depth-First Search (DFS) because it has to store all the nodes at each level.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads