Table of contents
1.
Introduction
2.
What is Depth-First Search (DFS)?
2.1.
How DFS Works
2.2.
Applications of DFS
2.3.
Implementation of DFS in Python
2.4.
Python
3.
What is BFS (Breadth-First Search)?
3.1.
How BFS Works
3.2.
Applications of BFS
3.3.
Implementation of BFS in Python
3.4.
Python
4.
Differences Between BFS and DFS
5.
Frequently Asked Questions
5.1.
Which algorithm is better for pathfinding, BFS or DFS?
5.2.
Why is DFS used in AI-based decision-making?
5.3.
What is the time complexity of BFS and DFS?
6.
Conclusion
Last Updated: Mar 15, 2025
Easy

Difference between BFS and DFS

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental graph traversal algorithms. BFS explores all neighbor nodes at the current depth before moving to the next level, making it ideal for finding the shortest path. DFS, on the other hand, explores as far as possible along a branch before backtracking, making it suitable for topological sorting and solving mazes.

Difference between BFS and DFS

In this article, we will compare BFS and DFS in terms of approach, implementation, time complexity, and use cases.

What is Depth-First Search (DFS)?

Depth-First Search (DFS) is an algorithm that explores a graph or tree by moving as deep as possible before backtracking. It uses a stack(either explicit or recursive) to keep track of nodes.

How DFS Works

  1. Start from the root node or an initial node.
     
  2. Visit the node and mark it as visited.
     
  3. Explore its neighbors (children) one by one.
     
  4. Move to the next neighbor and repeat until no more nodes can be visited.
     
  5. If a dead end is reached, backtrack to the previous node.

Applications of DFS

  • Solving mazes
     
  • Finding connected components in networks
     
  • Topological sorting
     
  • Solving puzzles like Sudoku

Implementation of DFS in Python

Below is the Python implementation of DFS using recursion:

  • Python

Python

def dfs(graph, node, visited=set()):
   if node not in visited:
       print(node, end=' ')
       visited.add(node)
       for neighbor in graph[node]:
           dfs(graph, neighbor, visited)
# Example graph represented as an adjacency list
graph = {
   'A': ['B', 'C'],
   'B': ['D', 'E'],
   'C': ['F', 'G'],
   'D': [],
   'E': [],
   'F': [],
   'G': []
}
print("DFS Traversal:")
dfs(graph, 'A')
You can also try this code with Online Python Compiler
Run Code

Output:

DFS Traversal:
A B D E C F G

 

Explanation:

  • The traversal starts at node 'A'.
     
  • It moves to 'B', then 'D', and backtracks to 'E'.
     
  • Then, it moves to 'C', explores 'F' and 'G'.
     
  • DFS explores as deep as possible before backtracking.

What is BFS (Breadth-First Search)?

Breadth-First Search (BFS) is an algorithm that explores a graph or tree level by level. It uses a queue to visit nodes in order of their distance from the starting point.

How BFS Works

  1. Start from the root node or an initial node.
     
  2. Visit the node and mark it as visited.
     
  3. Add all unvisited neighbors to a queue.
     
  4. Remove a node from the front of the queue and repeat the process.

Applications of BFS

  • Finding the shortest path in an unweighted graph
     
  • Web crawling
     
  • Network broadcasting
     
  • AI-based decision-making (like chess AI moves)

Implementation of BFS in Python

Below is the Python implementation of BFS using a queue:

  • Python

Python

from collections import deque
def bfs(graph, start):
   visited = set()
   queue = deque([start])
   while queue:
       node = queue.popleft()
       if node not in visited:
           print(node, end=' ')
           visited.add(node)
           queue.extend(graph[node])

# Example graph represented as an adjacency list
graph = {
   'A': ['B', 'C'],
   'B': ['D', 'E'],
   'C': ['F', 'G'],
   'D': [],
   'E': [],
   'F': [],
   'G': []
}
print("BFS Traversal:")
bfs(graph, 'A')
You can also try this code with Online Python Compiler
Run Code

Output:

BFS Traversal:
A B C D E F G

 

Explanation:

  • The traversal starts at node 'A'.
     
  • Nodes 'B' and 'C' are added to the queue.
     
  • Then, 'B' is visited, followed by its children ('D' and 'E').
     
  • Similarly, 'C' is visited, followed by its children ('F' and 'G').
     
  • The traversal continues until all nodes are visited.

Differences Between BFS and DFS

ParameterBFSDFS
Traversal OrderExplores nodes level by levelExplores nodes depth by depth
Data Structure UsedUses a queueUses a stack
Memory UsageMore memory-intensiveLess memory-intensive
CompletenessFinds the shortest path in an unweighted graphDoes not necessarily find the shortest path
ImplementationTypically implemented iterativelyTypically implemented recursively
ApplicationsShortest path in an unweighted graph, finding all connected componentsTopological sorting, finding strongly connected components

Frequently Asked Questions

Which algorithm is better for pathfinding, BFS or DFS?

BFS is better for pathfinding, especially in unweighted graphs, because it finds the shortest path. DFS is not ideal for this purpose.

Why is DFS used in AI-based decision-making?

DFS helps in solving puzzles and navigating decision trees, making it useful for AI applications like chess and game-solving.

What is the time complexity of BFS and DFS?

Both BFS and DFS have a time complexity of O(V + E), where V is the number of vertices and E is the number of edges.

Conclusion

In this article, we learned the difference between BFS (Breadth-First Search ) and DFS (Depth-First Search). BFS traverses level by level using a queue, making it ideal for finding the shortest path. DFS explores depth-wise using a stack( (or recursion), making it efficient for exhaustive searches. Choosing between them depends on the problem's requirements.

Live masterclass