Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- number_of_nodes = int(input())
- adj_list = {}
- status_list = {}
- stack = []
- for i in range(1, number_of_nodes + 1):
- adj_nodes = list(map(int, input(f"Enter the adj nodes of {i}: ").split()))
- adj_list[i] = adj_nodes
- status_list[i] = 0
- print(adj_list)
- starting_node = int(input("Enter the starting node: ", ))
- current_node = starting_node
- status_list[current_node] = 1
- stack.append(current_node)
- count = 0
- while True:
- if count < number_of_nodes:
- count += 1
- popped_val = stack[-1]
- del stack[-1]
- print(popped_val,"->",end=" ")
- vals = adj_list[popped_val]
- for x in vals:
- if status_list[x] == 0:
- status_list[x] = 1
- stack.append(x)
- if len(stack) >0:
- current_node = stack[-1]
- else:
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement