nathanwailes

Breadth-first search (recursive)

Mar 29th, 2024 (edited)
1,133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. """
  2. This is a stupid way to do BFS because there's no reason to do a recursive call instead of just having a while loop. It's maybe useful just to make it clear why recursion isn't needed for BFS and to make a person slightly more confident with recursion / BFS.
  3.  
  4. Common mistakes:
  5. - I forgot the base case.
  6. """
  7. from collections import deque
  8.  
  9. def bfs_r(graph, start):
  10.     visited = set()
  11.     queue = deque([start])
  12.     return bfsr_helper(graph, queue, visited)
  13.  
  14. def bfsr_helper(graph, queue, visited):
  15.     # We need to do this check because we'll get an error if we try to pop from
  16.     # an empty deque rather than a None return value:
  17.     if not queue:
  18.         return  # Base case: if the queue is empty, return
  19.  
  20.     vertex = queue.popleft()  # Dequeue the first node in the queue
  21.     if vertex not in visited:
  22.         print(vertex, end=" ")  # Process the current node
  23.         visited.add(vertex)  # Mark the current node as visited
  24.  
  25.         # Add all unvisited neighbors to the queue
  26.         for neighbor in graph[vertex]:
  27.             if neighbor not in visited:
  28.                 queue.append(neighbor)
  29.  
  30.     bfsr_helper(graph, queue, visited)  # Recursive call with the updated queue
  31.  
  32. graph = {
  33.     1 : [2,3],
  34.     2 : [4, 5],
  35.     3 : [5],
  36.     4 : [],
  37.     5 : [1],
  38. }
  39.  
  40. bfs_r(graph, 1) # Start BFS from vertex 1
Advertisement
Add Comment
Please, Sign In to add comment