Description

Breadth-First Search (BFS) is a graph traversal algorithm that visits all vertices at the current level (breadth) before moving on to the vertices at the next level. It is used to find shortest paths in graphs with unweighted edges (or equal edge weights), as well as to solve various graph problems such as checking connectivity or finding connected components.

Key Features:

  • Operating Principle: The algorithm starts at a chosen source vertex, explores all of its immediate neighboring vertices, and then moves on to explore their neighbors level by level. It uses a Queue (FIFO) data structure to keep track of the vertices to visit.
  • Visiting Order: Vertices closer to the source vertex are visited first.

Applications of BFS

  • Finding the shortest path in unweighted graphs or graphs with equal edge weights.
  • Checking graph connectivity (verifying if all vertices are reachable from a single starting vertex).
  • Finding connected components in undirected graphs.
  • Finding all possible paths or level-order relationships in a graph (e.g., in scheduling or state space search problems).

BFS Algorithm Steps

  1. Start at vertex s and push it into the queue.
  2. While the queue is not empty:
  3. Pop a vertex u from the queue.
  4. Visit all of its unvisited neighbors and push them into the queue.

For efficient implementation, a visited set is used to track visited vertices to avoid cycles and infinite loops.

Example

Consider the following graph:

     0
   /   \
  1     2
  \    / \
    3 4   5

The adjacency list representation for this graph is:

graph = {
    0: [1, 2],
    1: [0, 3],
    2: [0, 4, 5],
    3: [1],
    4: [2],
    5: [2]
}

Python Implementation

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)

How the Code Works

  1. We use a double-ended queue queue (collections.deque) to store vertices left to visit, allowing FIFO (First-In-First-Out) operations.
  2. We start at the start vertex (e.g., 0), adding it to both queue and the visited set to avoid reprocessing.
  3. In the while queue: loop, we pop a vertex from the left, process it (e.g., print it), and push all of its unvisited neighbors into the queue.
  4. The algorithm completes when all reachable vertices have been processed.

Complexity of BFS

  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges. Every vertex and edge is visited at most once.
  • Space Complexity: O(V), required to maintain the visited set and the queue.

Practical Uses of BFS

  1. Shortest Path in Unweighted Graphs: BFS guarantees the shortest path (in terms of edge count) from the start vertex to any other reachable vertex.
  2. Checking Connectivity: If all vertices are marked as visited after running BFS from a vertex, the graph is connected.
  3. Connected Components: Running BFS iteratively on unvisited vertices identifies distinct connected components in disconnected graphs.
  4. Maze Solving / Grid Traversal: BFS finds the shortest path through grids or mazes where each cell represents a vertex and valid moves represent edges.

Conclusion

Breadth-First Search (BFS) is a fundamental and powerful graph traversal algorithm. It is especially useful for shortest-path operations in unweighted graphs, checking connectivity, and component discovery. Its algorithm design is straightforward to implement and operates in linear time relative to graph size.