Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- def iterative_bfs(graph, start):
- visited = set() # Set to keep track of visited nodes.
- queue = deque([start]) # Initialize a queue with the starting vertex
- while queue: # While the queue is not empty
- vertex = queue.popleft() # Remove the vertex from the queue
- if vertex not in visited:
- visited.add(vertex) # Mark the vertex as visited
- print(vertex) # Process the vertex (for example, print it)
- # Add all unvisited neighbors to the queue
- for neighbor in graph[vertex]:
- if neighbor not in visited:
- queue.append(neighbor)
- # Example usage:
- # Define a graph as an adjacency list
- graph = {
- 1 : [2,3],
- 2 : [4, 5],
- 3 : [5],
- 4 : [],
- 5 : [1],
- }
- iterative_bfs(graph, 1) # Start BFS from vertex 1
Advertisement
Add Comment
Please, Sign In to add comment