Write a program to implement BFS

Write a program to implement BFS

from collections import deque

def bfs(graph, start_node):
    """
    Performs Breadth-First Search (BFS) on a graph.
    """
    # Set to keep track of visited nodes
    visited = set()
    # Queue to manage the nodes to visit (FIFO)
    queue = deque([start_node])
    # List to store the order of traversal
    traversal_order = []

    # Mark the start node as visited
    visited.add(start_node)

    while queue:
        # Dequeue a node from the front of the queue
        node = queue.popleft()
        traversal_order.append(node)

        # Iterate through all neighbors of the current node
        for neighbor in graph[node]:
            if neighbor not in visited:
                # Mark neighbor as visited and enqueue it
                visited.add(neighbor)
                queue.append(neighbor)

    return traversal_order

# --- Example Usage (Graph of Indian Cities) ---
# Representing the graph as an Adjacency List
city_graph = {
    'Mumbai': ['Delhi', 'Chennai', 'Hyderabad'],
    'Delhi': ['Mumbai', 'Kolkata', 'Jaipur'],
    'Chennai': ['Mumbai', 'Hyderabad', 'Bangalore'],
    'Hyderabad': ['Mumbai', 'Chennai', 'Bangalore'],
    'Kolkata': ['Delhi'],
    'Jaipur': ['Delhi'],
    'Bangalore': ['Chennai', 'Hyderabad']
}

print("BFS Traversal starting from 'Mumbai':")
result = bfs(city_graph, 'Mumbai')
print(" -> ".join(result))

print("\nBFS Traversal starting from 'Delhi':")
result = bfs(city_graph, 'Delhi')
print(" -> ".join(result))