Difference between Depth First Search and Breadth First Search

danimal92

Daniel Zaltsman

Posted on March 1, 2020

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.

💖 💪 🙅 🚩
danimal92
Daniel Zaltsman

Posted on March 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Demystifying Algorithms: Doubly Linked Lists
datastructures Demystifying Algorithms: Doubly Linked Lists

November 29, 2024

Demystifying Algorithms: Circular Linked Lists
datastructures Demystifying Algorithms: Circular Linked Lists

November 29, 2024

Demystifying Algorithms: Singly Linked Lists
datastructures Demystifying Algorithms: Singly Linked Lists

November 29, 2024

Estruturas de Dados: Lista
datastructures Estruturas de Dados: Lista

November 27, 2024