Advertisement
fadhiilrachman

BFS Shortest Path with Cost

Nov 25th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. import time
  2. start = time.time()
  3.  
  4. graph = {'A': [
  5.         10,
  6.         set(['B', 'C'])
  7.     ],
  8.     'B': [
  9.         20,
  10.         set(['A', 'D', 'E'])
  11.     ],
  12.     'C': [
  13.         30,
  14.         set(['A', 'F'])
  15.     ],
  16.     'D': [
  17.         40,
  18.         set(['B'])
  19.     ],
  20.     'E': [
  21.         50,
  22.         set(['B', 'F'])
  23.     ],
  24.     'F': [
  25.         60,
  26.         set(['C', 'E'])
  27.     ]
  28. }
  29.  
  30. def bfs_paths(graph, start, goal):
  31.     queue = [(start, [start])]
  32.     while queue:
  33.         (vertex, path) = queue.pop(0)
  34.         for next in graph[vertex][1] - set(path):
  35.             if next == goal:
  36.                 yield path + [next]
  37.             else:
  38.                 queue.append((next, path + [next]))
  39.  
  40. def bfs_shortest_path(graph, start, goal):
  41.     try:
  42.         return next(bfs_paths(graph, start, goal))
  43.     except StopIteration:
  44.         return None
  45.  
  46. def bfs_calc_cost(graph, route):
  47.     total_cost = 0
  48.     for i in route:
  49.         total_cost = total_cost + graph[i][0]
  50.     return total_cost
  51.  
  52. bfs_sp = bfs_shortest_path(graph, 'A', 'F')
  53. total_cost = bfs_calc_cost(graph, bfs_sp)
  54. print("Best Route: ", bfs_sp)
  55. print("Total cost: ", total_cost)
  56. print("Spent time:", time.time() - start, "seconds.")
  57. '''
  58. Best Route:  ['A', 'C', 'F']
  59. Total cost:  100
  60. Spent time: 2.002716064453125e-05 seconds.
  61. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement