codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

21 / 65 topics
20Depth-First Search (DFS)21Breadth-First Search (BFS)
Tutorials/Data Structures & Algorithms/Breadth-First Search (BFS)
🧮Data Structures & Algorithms

Breadth-First Search (BFS)

Updated 2026-04-20
3 min read

Breadth-First Search (BFS)

Introduction

Breadth-First Search (BFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph. It starts at the root node (or any arbitrary starting node in the case of an unrooted graph) and explores all neighbors at the present depth level before moving on to nodes at the next depth level. BFS is particularly useful for finding the shortest path in unweighted graphs.

Key Concepts

Graph Representation

Before diving into BFS, it's essential to understand how graphs can be represented. The two most common representations are:

  1. Adjacency List: An array of lists where each list contains the vertices that are adjacent to a particular vertex.
  2. Adjacency Matrix: A 2D array where the rows and columns represent vertices, and the value at matrix[i][j] indicates whether there is an edge between vertex i and vertex j.

BFS Algorithm

BFS uses a queue data structure to keep track of nodes to be explored. The algorithm can be summarized as follows:

  1. Initialize a queue and enqueue the starting node.
  2. Mark the starting node as visited.
  3. While the queue is not empty:
    • Dequeue a node from the front of the queue.
    • For each adjacent vertex that has not been visited, mark it as visited and enqueue it.

Implementation

Python Example

Below is a Python implementation of BFS using an adjacency list:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    
    while queue:
        vertex = queue.popleft()
        print(vertex, end=" ")
        
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

# Example usage
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

bfs(graph, 'A')

Explanation

  1. Graph Initialization: The graph is represented as a dictionary where each key is a vertex and its value is a list of adjacent vertices.
  2. Queue and Visited Set: A deque from the collections module is used for efficient queue operations. A set named visited keeps track of visited nodes to avoid processing them multiple times.
  3. BFS Loop: The loop continues until the queue is empty. In each iteration, a node is dequeued, printed, and its unvisited neighbors are enqueued.

Real-World Applications

1. Network Routing

BFS can be used in network routing to find the shortest path between two nodes in an unweighted graph. This is crucial for efficient data transmission over networks.

2. Peer-to-Peer Networks

In peer-to-peer networks, BFS helps in finding the nearest peers that can share files or resources.

3. Web Crawlers

Search engines use BFS to crawl web pages and build their index. They start from a seed page and explore all linked pages at the current depth before moving deeper.

Best Practices

  1. Choose the Right Data Structure: Use an adjacency list for sparse graphs and an adjacency matrix for dense graphs.
  2. Avoid Recursion: BFS is inherently iterative, so using recursion can lead to stack overflow in large graphs.
  3. Memory Management: Be mindful of memory usage, especially in large graphs. Consider using generators or lazy evaluation if necessary.

Conclusion

Breadth-First Search is a versatile and efficient algorithm for traversing graphs. Its ability to find the shortest path in unweighted graphs makes it invaluable in various applications. By understanding its implementation and best practices, you can effectively apply BFS to solve complex graph-related problems.

Further Reading

  • GeeksforGeeks: Breadth First Search (BFS) for a Graph
  • Coursera: Algorithms Part I by Princeton University
  • LeetCode: BFS Problems

PreviousDepth-First Search (DFS)Next Dijkstra's Algorithm

Recommended Gear

Depth-First Search (DFS)Dijkstra's Algorithm