nathanwailes

Breadth-first search (iterative)

Mar 24th, 2024 (edited)
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. from collections import deque
  2.  
  3. def iterative_bfs(graph, start):
  4.     visited = set() # Set to keep track of visited nodes.
  5.     queue = deque([start]) # Initialize a queue with the starting vertex
  6.    
  7.     while queue: # While the queue is not empty
  8.         vertex = queue.popleft() # Remove the vertex from the queue
  9.         if vertex not in visited:
  10.             visited.add(vertex) # Mark the vertex as visited
  11.             print(vertex) # Process the vertex (for example, print it)
  12.            
  13.             # Add all unvisited neighbors to the queue
  14.             for neighbor in graph[vertex]:
  15.                 if neighbor not in visited:
  16.                     queue.append(neighbor)
  17.  
  18. # Example usage:
  19. # Define a graph as an adjacency list
  20. graph = {
  21.     1 : [2,3],
  22.     2 : [4, 5],
  23.     3 : [5],
  24.     4 : [],
  25.     5 : [1],
  26. }
  27.  
  28. iterative_bfs(graph, 1) # Start BFS from vertex 1
Advertisement
Add Comment
Please, Sign In to add comment