Advertisement
sol4r

Depth for Search ( DFS ) [ DATA STRUCTURE ]

Dec 11th, 2020 (edited)
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. number_of_nodes = int(input())
  2. adj_list = {}
  3. status_list = {}
  4. stack = []
  5. for i in range(1, number_of_nodes + 1):
  6.     adj_nodes = list(map(int, input(f"Enter the adj nodes of {i}: ").split()))
  7.     adj_list[i] = adj_nodes
  8.     status_list[i] = 0
  9. print(adj_list)
  10. starting_node = int(input("Enter the starting node: ", ))
  11. current_node = starting_node
  12. status_list[current_node] = 1
  13. stack.append(current_node)
  14. count = 0
  15. while True:
  16.     if count < number_of_nodes:
  17.         count += 1
  18.         popped_val = stack[-1]
  19.         del stack[-1]
  20.         print(popped_val,"->",end=" ")
  21.         vals = adj_list[popped_val]
  22.         for x in vals:
  23.             if status_list[x] == 0:
  24.                 status_list[x] = 1
  25.                 stack.append(x)
  26.         if len(stack) >0:
  27.             current_node = stack[-1]
  28.         else:
  29.             break
  30.  
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement