Home / Blog /

Breadth First Search & Depth First Search

Graph Traversal Algorithms in AI

Uncodemy AI Team
June 20, 2025
12 min read
Scroll Down

Breadth First Search (BFS) and Depth First Search (DFS)

Overview of BFS and DFS

Que 2.4. Write a short note on: i. Breadth First Search (BFS) ii. Depth First Search (DFS).

Answer:

i. Breadth First Search (BFS): BFS is an algorithm for traversing or searching tree or graph data structures. It starts at the root node (or an arbitrary node) and explores all neighbor nodes at the current depth level before moving to nodes at the next depth level. It uses a queue to manage nodes.

Algorithm for BFS:

  1. Create a variable called NODE-LIST and set it to the initial state.
  2. Until a goal state is found or NODE-LIST is empty:
    1. Remove the first element from NODE-LIST and call it E-NODE.
    2. If E-NODE is a goal, return E-NODE as the answer.
    3. Otherwise, use the rule to generate a new state:
      1. If the new state is a goal, quit and return this state.
      2. Otherwise, add the new state to the end of NODE-LIST.
    4. Repeat.

ii. Depth First Search (DFS): DFS is an algorithm for traversing or searching tree or graph data structures. It starts at the root node and explores as far as possible along each branch before backtracking. It uses a stack (explicitly or via recursion).

Algorithm for DFS:

  1. If the initial state is a goal state, quit and return success.
  2. Otherwise, do the following until success or failure is signaled:
    1. Select an operator that has not yet been applied to the current state and apply it to produce a new state.
    2. If it is a goal, return and quit.
    3. Otherwise, continue with the new state.

Understanding BFS and DFS in AI

Breadth First Search (BFS) and Depth First Search (DFS) are fundamental uninformed search algorithms used in AI for traversing or searching graph and tree structures. They are essential for solving problems like pathfinding, maze-solving, and network analysis. BFS explores level by level, ensuring completeness and optimality in unweighted graphs, while DFS dives deep into each branch, making it memory-efficient but potentially incomplete in infinite graphs.

Key Insight

BFS prioritizes breadth, exploring all nodes at the current depth, while DFS prioritizes depth, exploring one branch fully before backtracking.

Example: In a social network, BFS can find the shortest path (e.g., degrees of separation) between two users, while DFS can explore deep connections (e.g., mutual interests) along a single path.

Did You Know?

BFS is used in GPS systems to find the shortest route, while DFS powers recursive backtracking in puzzle solvers like Sudoku.

Comparison: BFS vs. DFS

BFS and DFS differ in their traversal strategies, complexity, and applications. Below is a comparison table and textual diagram.

Feature BFS DFS
Traversal Strategy Level-order (breadth-first) Deep exploration (depth-first)
Data Structure Queue Stack (or recursion)
Time Complexity O(V + E) O(V + E)
Space Complexity O(b^d) (wider queues) O(d) (deeper stack)
Completeness Complete in finite graphs Incomplete in infinite graphs
Optimality Optimal in unweighted graphs Non-optimal
Applications Shortest path, GPS, social networks Puzzle-solving, topological sorting

Detailed Explanation of BFS and DFS

Below, we explore BFS and DFS using animated cards, with algorithms, complexities, and applications.

Breadth First Search (BFS)

BFS explores nodes level by level using a queue, ensuring completeness and optimality in unweighted graphs. It’s ideal for finding shortest paths in mazes or networks.

Complexity: Time: O(V + E), Space: O(b^d), where V is vertices, E is edges, b is branching factor, d is depth.

Depth First Search (DFS)

DFS explores one branch fully using a stack or recursion, backtracking when needed. It’s memory-efficient but may miss solutions in infinite graphs.

Complexity: Time: O(V + E), Space: O(d).

Traversal Workflows: BFS and DFS

Below is a textual diagram illustrating BFS and DFS traversal on a sample graph (A → [B, C], B → [D, E], C → [F]).

Visualizing BFS and DFS

Below are textual visualizations of BFS and DFS exploration patterns.

Technical Insights for Students

For students mastering BFS and DFS, understanding their mechanics and trade-offs is crucial:

  • Data Structures: BFS uses a queue (`collections.deque` in Python); DFS uses a stack or recursion.
  • Graph Representation: Use adjacency lists for sparse graphs to optimize O(V + E) complexity.
  • Complexity Analysis: BFS’s space complexity (O(b^d)) makes it memory-intensive; DFS’s O(d) is efficient for deep graphs.
  • Applications: Implement BFS for shortest path problems (e.g., GPS); use DFS for topological sorting or cycle detection.
  • Optimizations: Use a `visited` set to avoid cycles in graphs.

Mathematical Formulation: For a graph with V vertices and E edges, both BFS and DFS have O(V + E) time complexity, but BFS’s queue size can reach O(b^d) in trees, while DFS’s stack is O(d).

Practical Tip: Implement BFS and DFS for a maze-solving problem on Google Colab, comparing their performance on large grids.

Code Example: BFS and DFS in Python

Below is a Python implementation of BFS and DFS for graph traversal.

from collections import deque

# BFS Implementation
def bfs(graph, start):
    visited = set()
    queue = deque([start])
    traversal = []
    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.add(node)
            traversal.append(node)
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)
    return traversal

# DFS Implementation (Recursive)
def dfs(graph, start, visited=None, traversal=None):
    if visited is None:
        visited = set()
    if traversal is None:
        traversal = []
    if start not in visited:
        visited.add(start)
        traversal.append(start)
        for neighbor in graph[start]:
            dfs(graph, neighbor, visited, traversal)
    return traversal

# Example graph (adjacency list)
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

# Run BFS and DFS
bfs_result = bfs(graph, 'A')
dfs_result = dfs(graph, 'A')
print(f"BFS Traversal: {bfs_result}")  # A, B, C, D, E, F
print(f"DFS Traversal: {dfs_result}")  # A, B, D, E, C, F
                    

This code demonstrates BFS’s level-order traversal and DFS’s deep exploration, with outputs showing their distinct traversal orders.

Key Takeaways

  • BFS explores level by level, using a queue, ideal for shortest path problems.
  • DFS explores one branch fully, using a stack or recursion, suitable for deep searches.
  • Both have O(V + E) time complexity, but BFS is memory-intensive, while DFS is space-efficient.
  • Mastering BFS and DFS is essential for AI applications like pathfinding and network analysis.

Ready to Master Graph Traversal Algorithms?

Join Uncodemy’s AI Certification Program to learn BFS, DFS, and advanced AI techniques.

Start Learning Today

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses

Uncodemy AI Expert

About the Author

Dr. Sarah Johnson is Uncodemy's lead AI instructor with 10+ years of experience in machine learning and neural networks. She has worked with leading tech companies and now focuses on training the next generation of AI professionals.