Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. import pdb
  2. from collections import deque
  3.  
  4. graph = {'boston': set(['new york']),
  5. 'new york': set(['pittsburg', 'philly']),
  6. 'philly': set(['baltimore']),
  7. 'baltimore': set(['washington']),
  8. 'pittsburg': set(['minneapolis']),
  9. 'washington': set(['minneapolis'])
  10. }
  11.  
  12.  
  13.  
  14. def bfs_paths(graph, start, goal):
  15. queue = deque()
  16. queue.append((start, [start]))
  17. result = []
  18. found = False
  19. # node, path
  20. while queue:
  21. (vertex, path) = queue.popleft()
  22. for next in graph[vertex] - set(path):
  23. if next == goal:
  24. result.append(path + [next])
  25. found = True
  26. else:
  27. queue.append((next, path + [next]))
  28. # pdb.set_trace()
  29. if found:
  30. break
  31.  
  32. return result
  33.  
  34.  
  35. print(bfs_paths(graph, 'boston', 'minneapolis'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement