if given a graph problem how do we know whether we need to use bfs or dfs algorithm??? or when do we use dfs algorithm or bfs algorithm. What are the differences and advantages of one over other?
DFS traversal is optimal for those graphs in which solutions are away from the source vertex. BFS is slower than DFS. DFS is faster than BFS. It is not suitable for the decision tree because it requires exploring all the neighboring nodes first.
1) Breadth first search (BFS)The closed list records the states that have been examined and whose children have been generated. The order of removing the states from the open list will be the order of searching. The open is maintained as a queue on the first in first out data structure.
BFS uses Queue to find the shortest path. DFS uses Stack to find the shortest path. BFS is better when target is closer to Source. DFS is better when target is far from source.
BFS is going to use more memory depending on the branching factor... however, BFS is a complete algorithm... meaning if you are using it to search for something in the lowest depth possible, BFS will give you the optimal solution.
BFS space complexity is O(b^d)
... the branching factor raised to the depth (can be A LOT of memory).
DFS on the other hand, is much better about space however it may find a suboptimal solution. Meaning, if you are just searching for a path from one vertex to another, you may find the suboptimal solution (and stop there) before you find the real shortest path. DFS space complexity is O(|V|)
... meaning that the most memory it can take up is the longest possible path.
They have the same time complexity.
In terms of implementation, BFS is usually implemented with Queue
, while DFS uses a Stack
.
breadth first searches for siblings first. depth first obviously searches for children first. So, I guess it would depend on what kind of searching you're looking to do. relationship type searches across fields would probably lend itself to bfs, where hierarchical (trees, folders, ranks, etc) would be more suited as a dfs.
Both the graph traversals promise one thing: a complete traversal of the graph, visiting every vertex in the graph. If you have memory constraints, DFS is a good choice, as BFS takes up a lot of space. So, choosing between these two depends on your requirement.
Want to find the (strongly/)connected components of the graph? Or solve the maze? Or sudoku? Use DFS. If you look closely, the Pre-Order, Post-Order and In-Order are all variants of the DFS. So, yes, that's some interesting applications.
BFS if you want to test if a graph is bipartite, find the shortest path between two nodes or applications that require such tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With