Breadth First Search
Breadth First Search (BFS) is an algorithm for traversing or searching tree. (For example, you can find the shortest path from one node to another in an unweighted graph.)
![Breadth First Search Traversal](../img/bfs.jpg)
Method¶
BFS is a traversing algorithm where you should start traversing from a selected node (source or starting node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are directly connected to source node). You must then move towards the next-level neighbour nodes. [1]
• As the name BFS suggests, you are required to traverse the graph breadthwise as follows: • First move horizontally and visit all the nodes of the current layer • Add to the queue neighbour nodes of current layer. • Move to the next layer, which are in the queue
Example question: Given a unweighted graph, a source and a destination, we need to find shortest path from source to destination in the graph in most optimal way?
Complexity¶
The time complexity of BFS is \(O(V + E)\), where \(V\) is the number of nodes and \(E\) is the number of edges.