Breadth-First Search (BFS) is a graph traversal algorithm used to explore nodes and edges in a graph systematically. It starts from a given source node and explores all its neighbors before moving on to their neighbors, ensuring the search progresses level by level.
Key Characteristics of BFS
- Level-order traversal: Visits nodes layer by layer (or distance by distance) from the source.
- Uses a queue: It relies on the FIFO (First In, First Out) principle for node exploration.
- Time complexity: O(V+E)O(V + E), where VV is the number of vertices and EE is the number of edges.
- Space complexity: O(V)O(V), for the visited list and queue.
- Applicable for:
- Finding the shortest path in an unweighted graph.
- Checking graph connectivity.
- Solving puzzles and problems like maze traversal.
BFS Algorithm
- Start with the source node.
- Mark the source node as visited.
- Add the source node to a queue.
- While the queue is not empty:
- Remove the front node from the queue.
- Visit all its unvisited neighbors, mark them as visited, and add them to the queue.
Python Implementation
Output for the Example
Given the graph above, the BFS traversal starting from 'A'
is:
Explanation
- Start at
'A'
, visit its neighbors'B'
and'C'
. - Move to
'B'
, visit its neighbors'D'
and'E'
. - Move to
'C'
, visit its neighbor'F'
. - Continue until all nodes are visited.
Advantages
- Guarantees the shortest path in an unweighted graph.
- Simple and easy to implement.
Disadvantages
- Requires extra memory for the queue.
- May become slow for dense or large graphs.
BFS is foundational for solving many graph-based problems, such as finding connected components, detecting cycles, and pathfinding in games.