DEV Community

Cover image for Difference between Depth First Search and Breadth First Search
Daniel Zaltsman
Daniel Zaltsman

Posted on

Difference between Depth First Search and Breadth First Search

Most likely, if you are traversing a tree you will be using either of these two methods: Breadth First Search or Depth First Search. Both of these methods will visit all edges and vertices of a graph but will traverse it differently.

Depth First Search will follow a path from the starting node to an ending node, then another path from start to end until all the nodes are visited. DFS starts the traversal from the root node and visits nodes as far as possible from the root node. This method is implemented using a stack data structure and generally requires less memory than BFS.

Breadth First Search proceeds level by level visiting all nodes on one level before moving on to the next. BFS starts traversal from the root node and visits nodes in a level by level manner. It is usually implemented using a queue structure and generally requires more memory than DFS.

When to use BFS vs DFS

BFS is optimal for finding the shortest distance, and is more suitable for searching vertices which are closer to the given source.

DFS is more suitable when there are solutions away from source. DFS is more suitable for game or puzzle problems. We make a decision, then explore all paths through this decision. And if this decision leads to win situation, we stop.

Top comments (1)

Collapse
 
arunaa2783 profile image
Arunaa G T

Nice