Can anybody give a simple explanation on BFS and DFS?
I want to understand when to prefer BFS over DFS.
1 Answer
BFS and DFS are both graph traversing algorithms, the difference between them is the way each algorithm traverses the graph.
DFS, Imagine you have the following graph and we want to start traversing from node 1:
1
/ \
2 3
/ \ \
4 5 6
DFS means Depth first search, so it will traverse the graph in this way:
- start from node
1then look for its children. It finds node2. - go to node
2then look for its children. It finds node4. - go to node
4then it finds that it has no children. - go
Upto node2again and see its other children. It finds node5. - go to node
5then it find that it has no children. - go up again to node
2and find out that it has no more children. - go up to node
1then look for its children. It finds node3. - go to node
3then look for its children. It find node6. - go to node
6and find out that it has no children. - go up to node
3and find out that it has no more children. - go up to node
1and find out that it has no more children, hence the graph traversal has finished at this point.
If you note here how this algorithm goes in depth first, so once it found that node 2 is a child of node 1 it went for it and started looking for its children without caring about the rest of children of node 1 (node 3) at this point of time, then after going to deepest possible node (nodes 4, 5) it started to go Up looking for the rest of children of node 1.
On the other hand, consider we want to traverse the same graph using BFS algorithm. When using BFS you start thinking of graph nodes as levels, each level is closer than the level after it relative to the node you start traversing from. which means:
1 (level 0)
/ \
2 3 (level 1)
/ \ \
4 5 6 (level 2)
So traversing the graph will be:
- start from node
1then look for its children (nodes2,3) [the next level]. - traverse nodes of level 1 (
2,3) and look for their children (nodes4,5,6) [the next level]. - traverse nodes of level 2 (
4,5,6) and look for this children (no children) [no next level]. - then graph traversal ends at this point.
You can realize here that the direct children of a node (the next level) are always the closest nodes to it, and hence the advantage of using BFS over DFS is that it can guarantee for you that you reach from node x to node y using the shortest path possible.
But be aware that BFS algorithm can't find you the shortest path for all types of graph. The graph I mentioned in this example is unweighted graph (a graph in which all edges/paths are the same). If your graph is weighted (edges/paths have weights and not the same) then you have to use another algorithm that takes this into consideration (like Dijkstra).