Breadth First Search
Last updated
Was this helpful?
Last updated
Was this helpful?
Start by exploring the nodes at a given depth before proceeding to the next level. This means that we will explore the children of nodes before we proceed to the children of the children.
This is useful when we want to find the minimal path length solution, if one exists. The disadvantage is that we need to traverse the complete tree which results in a lot of nodes.
BFS Uses a queue structure to hold all unexplored nodes. The order in which nodes are placed on the queue determine the type or search.
Place root node s on the queue
If queue is empty. return false and stop
If first element on the queue is a goal node g. Return success and stop otherwise.
Remove and expand the first element from the queue and place all the children at the end of the queue in any order.
Return to step 2
Input: Graph G, Vertice of G called v.
Output: All vertices reachable from v labeled as discovered.
We can divide the connections into classes as we did with DFS:
TreeNode: Connection with undiscovered node
BackEdge: Connection with ascendant.
CrossEdge: Connection with no ascendants and descendants.
We can not have forward edges, this because we start from a root node and go downwards.
BFS has many applications, some of them are:
Testing a graph for it's bipartiteness.
Finding loops in undirected graphs.
Finding the shortest path between 2 nodes u and v.
Initialisation:
We put elements on queue and dequeue them, these operations are O(1), so we get
We go through each neighbor, this is for the neighbor lists and for the neighbor matrix.
So depending on the way we represent the graph we get for the list and for the matrix.