Advertisement
fadhiilrachman

BFS Shortest Path with Neighbor Cost

Nov 25th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import time
  2. start = time.time()
  3.  
  4. graph = {'M': set(['U', 'H']),
  5.     'U': set(['M', 'D', 'A']),
  6.     'H': set(['M', 'F']),
  7.     'A': set(['U', 'I']),
  8.     'D': set(['A', 'F']),
  9.     'F': set(['H', 'R']),
  10.     'I': set(['L']),
  11.     'L': set(['D', 'C']),
  12.     'R': set(['L', 'N']),
  13.     'C': set(['I', 'N']),
  14.     'N': set(['L'])
  15. }
  16.  
  17. costs = {
  18.     'M': {
  19.         'U': 5,
  20.         'H': 8
  21.     },
  22.     'U': {
  23.         'M': 10,
  24.         'D': 6,
  25.         'A': 9
  26.     },
  27.     'H': {
  28.         'M': 12,
  29.         'F': 3
  30.     },
  31.     'A': {
  32.         'U': 2,
  33.         'I': 15
  34.     },
  35.     'D': {
  36.         'A': 11,
  37.         'F': 13
  38.     },
  39.     'F': {
  40.         'H': 4,
  41.         'R': 1
  42.     },
  43.     'I': {
  44.         'L': 7
  45.     },
  46.     'L': {
  47.         'D': 16,
  48.         'C': 18
  49.     },
  50.     'R': {
  51.         'L': 17,
  52.         'N': 20
  53.     },
  54.     'C': {
  55.         'I': 21,
  56.         'N': 19
  57.     },
  58.     'N': {
  59.         'L': 14
  60.     }
  61. }
  62.  
  63. def bfs_paths(graph, costs, start, goal):
  64.     route, list_cost = [(start, [start])], []
  65.     while route:
  66.         (vertex, path) = route.pop(0)
  67.         for next in graph[vertex] - set(path):
  68.             # tetangganya juga diitung iyh
  69.             list_cost.append(costs[vertex][next])
  70.             if next == goal:
  71.                 yield path + [next], list_cost
  72.             else:
  73.                 route.append((next, path + [next]))
  74.  
  75. def bfs_shortest_path(graph, costs, start, goal):
  76.     try:
  77.         return next(bfs_paths(graph, costs, start, goal))
  78.     except StopIteration:
  79.         return None
  80.  
  81. bfs_sp, list_cost = bfs_shortest_path(graph, costs, 'M', 'N')
  82. print("Best route: ", bfs_sp)
  83. print("Total cost: ", sum(list_cost))
  84. print("Spent time:", time.time() - start, "seconds.")
  85.  
  86. '''
  87. Best route:  ['M', 'H', 'F', 'R', 'N']
  88. Total cost:  91
  89. Spent time: 3.24249267578125e-05 seconds.
  90. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement