Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- start = time.time()
- graph = {'A': [
- 10,
- set(['B', 'C'])
- ],
- 'B': [
- 20,
- set(['A', 'D', 'E'])
- ],
- 'C': [
- 30,
- set(['A', 'F'])
- ],
- 'D': [
- 40,
- set(['B'])
- ],
- 'E': [
- 50,
- set(['B', 'F'])
- ],
- 'F': [
- 60,
- set(['C', 'E'])
- ]
- }
- def bfs_paths(graph, start, goal):
- queue = [(start, [start])]
- while queue:
- (vertex, path) = queue.pop(0)
- for next in graph[vertex][1] - set(path):
- if next == goal:
- yield path + [next]
- else:
- queue.append((next, path + [next]))
- def bfs_shortest_path(graph, start, goal):
- try:
- return next(bfs_paths(graph, start, goal))
- except StopIteration:
- return None
- def bfs_calc_cost(graph, route):
- total_cost = 0
- for i in route:
- total_cost = total_cost + graph[i][0]
- return total_cost
- bfs_sp = bfs_shortest_path(graph, 'A', 'F')
- total_cost = bfs_calc_cost(graph, bfs_sp)
- print("Best Route: ", bfs_sp)
- print("Total cost: ", total_cost)
- print("Spent time:", time.time() - start, "seconds.")
- '''
- Best Route: ['A', 'C', 'F']
- Total cost: 100
- Spent time: 2.002716064453125e-05 seconds.
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement