Untitled

 avatar
unknown
plain_text
11 days ago
980 B
9
Indexable
from collections import deque

# Function to perform BFS on the graph
def bfs(graph, start_node):
    visited = set()       # Set to track visited nodes
    queue = deque([start_node])  # Queue for BFS, starting with the start node
    
    while queue:
        node = queue.popleft()  # Pop the first node from the queue
        
        if node not in visited:
            print(node, end=" ")  # Print the node (could be any action)
            visited.add(node)  # Mark the node as visited
            
            # Add all unvisited neighbors to the queue
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)

# Example of an undirected graph represented as an adjacency list
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

# Call the BFS function
print("BFS Traversal starting from node A:")
bfs(graph, 'A')
Leave a Comment