Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- 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.
- What determines the different order of the handling of the nodes between the iterative and recursive versions of this code
- is the fact that in the iterative version the 'for neighbor in graph' finishes adding all of the neighbors before the next
- neighbor is popped off the stack, so the later neighbors get recursed before the earlier neighbors, whereas in the recursive
- version the neighbors are recursed immediately as they're encountered within that for loop, so the earlier neighbors get
- recursed before the later neighbors.
- 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.
- Pseudocode:
- # dfs_r - need graph, current_node, and visited
- # Initialize the set of visited nodes
- # Mark the current node as visited
- # Process the current node (for example, print it)
- # Loop through neighbors and recursively visit each
- """
- def dfs_r(graph, start, visited=None):
- if visited is None:
- visited = set() # Initialize the set of visited nodes
- visited.add(start) # Mark the current node as visited
- print(start) # Process the current node (for example, print it)
- for neighbor in graph[start]:
- if neighbor not in visited:
- dfs_r(graph, neighbor, visited) # Recursively visit unvisited neighbors
- graph = {
- 1 : [2, 3],
- 2 : [4, 5],
- 3 : [],
- 4 : [5],
- 5 : [1],
- }
- dfs_r(graph, 1) # Start from vertex 1
Advertisement
Add Comment
Please, Sign In to add comment