Guest User

Untitled

a guest
Nov 18th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. graph = {
  2. 'A': set(['B']),
  3. 'B': set(['C']),
  4. 'C': set(['D']),
  5. }
  6.  
  7.  
  8. def bfs_paths(graph, start, goal):
  9. queue = [(start, [start])]
  10. while queue:
  11. (vertex, path) = queue.pop(0)
  12. for next in graph[vertex] - set(path):
  13. if next == goal:
  14. yield path + [next]
  15. else:
  16. queue.append((next, path + [next]))
  17.  
  18.  
  19. def shortest_path(graph, start, goal):
  20. try:
  21. return next(bfs_paths(graph, start, goal))
  22. except StopIteration:
  23. return None
  24.  
  25.  
  26. print(shortest_path(graph, 'A', 'D'))
Add Comment
Please, Sign In to add comment