Certainly! Let's use BFS to solve a common problem: finding the shortest path in an unweighted graph. We'll represent the graph using an adjacency list and perform BFS to find the shortest path from a start node to a target node.
Example Problem
Given the following undirected graph:
Graph:
A -> B, C
B -> A, D, E
C -> A, F
D -> B
E -> B, F
F -> C, E
We want to find the shortest path from node A to node F.
Python Implementation
Here's a complete Python implementation of BFS to solve this problem:
from collections import deque
def bfs_shortest_path(graph, start, target):
# Initialize the queue for BFS with the start node
queue = deque([(start, [start])]) # Each element is a tuple (current_node, path_to_current_node)
visited = set()
while queue:
current_node, path = queue.popleft()
if current_node == target:
return path # Return the path if the target node is reached
if current_node not in visited:
visited.add(current_node)
# Add all unvisited neighbors to the queue
for neighbor in graph[current_node]:
if neighbor not in visited:
queue.append((neighbor, path + [neighbor]))
return None # Return None if there is no path to the target node
# Define the graph as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# Find the shortest path from 'A' to 'F'
start_node = 'A'
target_node = 'F'
shortest_path = bfs_shortest_path(graph, start_node, target_node)
if shortest_path:
print(f"Shortest path from {start_node} to {target_node}: {shortest_path}")
else:
print(f"No path from {start_node} to {target_node} found.")
Explanation
-
Initialization:
- We initialize a queue with the start node and the path to the start node.
- We use a set to keep track of visited nodes to avoid processing a node more than once.
-
BFS Loop:
- We dequeue the front element of the queue.
- If the current node is the target node, we return the path.
- If the current node hasn’t been visited, we mark it as visited and enqueue all its unvisited neighbors along with the path to reach them.
-
Result:
- The function returns the shortest path from the start node to the target node. If no path is found, it returns
None.
Output
Running the above code will output:
Shortest path from A to F: ['A', 'C', 'F']
This indicates that the shortest path from node A to node F is A -> C -> F.