can you tell me how to code bfs in python
- User
can you tell me how to code bfs in python
Assistant
pythonfrom collections import deque def bfs(graph, start): # Initialize queue with the starting node queue = deque([start]) # Keep track of visited nodes visited = set([start]) # For tracking traversal order (optional) traversal = [start] while queue: # Dequeue current node current = queue.popleft() # Process all neighbors for neighbor in graph[current]: if neighbor not in visited: queue.append(neighbor) visited.add(neighbor) traversal.append(neighbor) return traversal # Example usage if __name__ == "__main__": # Sample graph as adjacency list graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } result = bfs(graph, 'A') print(result) # ['A', 'B', 'C', 'D', 'E', 'F']
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.