Advertisement
Kamend1

Exam Prep Gateways - Kamen Dimitrov

Jul 30th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. from collections import deque
  2.  
  3. nodes = int(input())
  4. edges = int(input())
  5.  
  6. graph = []
  7.  
  8. for _ in range(nodes + 1):
  9. graph.append([])
  10.  
  11. for _ in range(edges):
  12. source, destination = [int(x) for x in input().split()]
  13. graph[source].append(destination)
  14.  
  15. start_node = int(input())
  16. end_node = int(input())
  17.  
  18. visited = [False] * (nodes + 1)
  19. parent = [None] * (nodes + 1)
  20.  
  21. visited[start_node] = True
  22. queue = deque([start_node])
  23.  
  24. while queue:
  25. node = queue.popleft()
  26. if node == end_node:
  27. break
  28. for child in graph[node]:
  29. if visited[child]:
  30. continue
  31. visited[child] = True
  32. queue.append(child)
  33. parent[child] = node
  34.  
  35. path = deque()
  36. node_travel = end_node
  37. while node_travel is not None:
  38. path.appendleft(node_travel)
  39. node_travel = parent[node_travel]
  40.  
  41. if path:
  42. print(*path, sep=' ')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement