21. BFS (Breadth-First Search)
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
- Start at vertex
sand push it into the queue. - While the queue is not empty:
- Pop a vertex
ufrom the queue. - 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
- We use a double-ended queue
queue(collections.deque) to store vertices left to visit, allowing FIFO (First-In-First-Out) operations. - We start at the
startvertex (e.g.,0), adding it to bothqueueand thevisitedset to avoid reprocessing. - 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. - The algorithm completes when all reachable vertices have been processed.
Complexity of BFS
- Time Complexity: O(V + E), where
Vis the number of vertices andEis the number of edges. Every vertex and edge is visited at most once. - Space Complexity: O(V), required to maintain the
visitedset and thequeue.
Practical Uses of BFS
- Shortest Path in Unweighted Graphs: BFS guarantees the shortest path (in terms of edge count) from the start vertex to any other reachable vertex.
- Checking Connectivity: If all vertices are marked as visited after running BFS from a vertex, the graph is connected.
- Connected Components: Running BFS iteratively on unvisited vertices identifies distinct connected components in disconnected graphs.
- 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.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me