Difference between BFS and DFS

Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.

Difference between BFS and DFS

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.Â
Example:

Input:
A
/ \
B C
/ / \
D E F

Output:Â

A, B, C, D, E, F

Depth First Search (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.Â
Example:Â

Input:
A
/ \
B D
/ / \
C E F

Output:Â

A, B, C, D, E, F

Difference Between BFS and DFS:

ParametersBFSDFS
Stands forBFS stands for Breadth First Search.DFS stands for Depth First Search.
Data StructureBFS(Breadth First Search) uses Queue data structure for finding the shortest path.DFS(Depth First Search) uses Stack data structure.
DefinitionBFS 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.
Conceptual DifferenceBFS builds the tree level by level.DFS builds the tree sub-tree by sub-tree.
Approach usedIt works on the concept of FIFO (First In First Out).Â It works on the concept of LIFO (Last In First Out).
Suitable forBFS is more suitable for searching vertices closer to the given source.DFS is more suitable when there are solutions away from source.
ApplicationsBFS 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.

Please also see BFS vs DFS for Binary Tree for the differences for a Binary Tree Traversal.Â

Previous
Next