nathanwailes

Depth-first search (recursive)

Mar 24th, 2024 (edited)
739
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. """
  2. You'll see that the iterative version prints out 1-3-2-5-4, while the recursive version prints out 1-2-4-5-3.
  3. What determines the different order of the handling of the nodes between the iterative and recursive versions of this code
  4. is the fact that in the iterative version the 'for neighbor in graph' finishes adding all of the neighbors before the next
  5. neighbor is popped off the stack, so the later neighbors get recursed before the earlier neighbors, whereas in the recursive
  6. version the neighbors are recursed immediately as they're encountered within that for loop, so the earlier neighbors get
  7. recursed before the later neighbors.
  8. So, for example, if the graph says "1: [2, 3]", iterative DFS will have the 3 visited first, recursive DFS will have the 2 visited first.
  9.  
  10. Pseudocode:
  11.  
  12. # dfs_r - need graph, current_node, and visited
  13.    # Initialize the set of visited nodes
  14.    # Mark the current node as visited
  15.    # Process the current node (for example, print it)
  16.    # Loop through neighbors and recursively visit each
  17. """
  18. def dfs_r(graph, start, visited=None):
  19.     if visited is None:
  20.         visited = set() # Initialize the set of visited nodes
  21.        
  22.     visited.add(start) # Mark the current node as visited
  23.     print(start) # Process the current node (for example, print it)
  24.    
  25.     for neighbor in graph[start]:
  26.         if neighbor not in visited:
  27.             dfs_r(graph, neighbor, visited) # Recursively visit unvisited neighbors
  28.  
  29. graph = {
  30.     1 : [2, 3],
  31.     2 : [4, 5],
  32.     3 : [],
  33.     4 : [5],
  34.     5 : [1],
  35. }
  36. dfs_r(graph, 1)  # Start from vertex 1
Advertisement
Add Comment
Please, Sign In to add comment