top of page

Compare and contrast Depth-first search and Breadth-first search


Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees.


BFS, Breadth-First Search, is a vertex-based technique for finding the shortest path in the graph. It uses a Queue data structure that follows first in first out. In BFS, one vertex is selected at a time when it is visited and marked then its adjacent are visited and stored in the queue. It is slower than DFS.


DFS, Depth First Search, is an edge-based technique. It uses the Stack data structure and performs two stages, first visited vertices are pushed into the stack, and second if there are no vertices then visited vertices are popped.


Let us tabulate the differences for the two.




BREADTH FIRST SEARCH

DEPTH FIRST SEARCH

BFS(Breadth First Search) uses Queue data structure.

DFS(Depth First Search) uses Stack data structure.

BFS is a traversal approach in which we first walk through all nodes on the same level before moving on to the next level.

DFS is also a traversal approach in which the traverse begins at the root node and proceeds through the nodes as far as possible until we reach the node with no unvisited nearby nodes.

It works on the concept of FIFO (First In First Out).

It works on the concept of LIFO (Last In First Out).

BFS always finds the shortest path, if available.

DFS may or may not find the shortest path.

BFS is more suitable for searching vertices closer to the given source.

DFS is more suitable when there are solutions away from source.

BFS is used in various applications such as bipartite graphs, shortest paths, etc.

DFS is used in various applications such as acyclic graphs and finding strongly connected components etc.


207 views0 comments
logo

Crookshanks Academy is an online learning platform with free netflix styled courses.

Crookshanks Academy 2023 ©️ All Rights Reserved

This content is protected from right clicks.
bottom of page