Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- graph = {
- 'A': set(['B']),
- 'B': set(['C']),
- 'C': set(['D']),
- }
- def bfs_paths(graph, start, goal):
- queue = [(start, [start])]
- while queue:
- (vertex, path) = queue.pop(0)
- for next in graph[vertex] - set(path):
- if next == goal:
- yield path + [next]
- else:
- queue.append((next, path + [next]))
- def shortest_path(graph, start, goal):
- try:
- return next(bfs_paths(graph, start, goal))
- except StopIteration:
- return None
- print(shortest_path(graph, 'A', 'D'))
Add Comment
Please, Sign In to add comment