What is BFS ?
What is DFS ?
Difference between BFS vs DFS ?
Basis |
BFS |
DFS |
1. Nature - |
Explores level by level, i.e., it explores all the
neighbor nodes at the current depth before moving on to nodes at the next
depth. |
Explores as far as possible along one branch before
backtracking. |
2. Data Structure: |
Uses a queue data structure to keep track of the nodes to be explored. |
Uses a stack (or recursion) to keep track of nodes to be explored. |
3. Memory Usage: |
Generally requires more memory because it needs to store
all nodes at the current level. |
Typically uses less memory as it only needs to store a
stack of nodes corresponding to the current branch. |
4. Implementation: |
Iterative implementation is usually preferred using a queue. |
Recursive implementation is common, but it can also be implemented using
a stack. |
5. Completeness |
Guaranteed to find the shortest path in an unweighted
graph. |
Does not guarantee the shortest path. |
6. Time Complexity: |
Generally has higher time complexity compared to DFS. |
Usually has a lower time complexity. |
7. Use Cases : |
Useful in finding the shortest path, puzzle solving, and
scenarios where you want to explore all possibilities level by level. |
Useful in topological sorting, finding connected
components, and scenarios where you want to explore as far as possible along
each branch. |
8. Path vs. Space |
May not be practical for dense graphs due to its space complexity. |
Typically more memory-efficient, especially for sparse graphs. |
9. Applications : |
Web crawling, shortest path problems, network
broadcasting. |
Topological sorting, solving mazes, finding connected
components. |
10. Order of Visitation |
Nodes are visited in the order they are discovered, level by level. |
Nodes are visited in a depthward motion until a dead end is reached, and
then the algorithm backtracks. |