Guest User

Dijkstra

a guest
Jun 11th, 2015
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. def dijkstra(graph_in, src, dest, visited=None, distances=None, predecessors=None) -> list:
  2.  
  3.     if not predecessors:
  4.         predecessors = {}
  5.     if not distances:
  6.         distances = {}
  7.     if not visited:
  8.         visited = []
  9.     global g_path
  10.     if src not in graph_in:
  11.         raise TypeError("No source in graph")
  12.     if dest not in graph_in:
  13.         raise TypeError("No target in graph")
  14.  
  15.     if src == dest:
  16.         path = []
  17.         pred = dest
  18.         while pred is not None:
  19.             path.append(pred)
  20.             g_path.append(pred)
  21.             pred = predecessors.get(pred, None)
  22.         g_path = g_path[::-1]
  23.         print("Shortest path: " + str(path[::-1]))
  24.         return path
  25.     else:
  26.         if not visited:
  27.             distances[src] = 0
  28.  
  29.         for neighbour in graph_in[src]:
  30.             if neighbour not in visited:
  31.                 new_distance = distances[src] + graph_in[src][neighbour]
  32.                 if new_distance < distances.get(neighbour, float('inf')):
  33.                     distances[neighbour] = new_distance
  34.                     predecessors[neighbour] = src
  35.  
  36.         visited.append(src)
  37.  
  38.         unvisited = {}
  39.  
  40.         for k in graph_in:
  41.             if k not in visited:
  42.                 unvisited[k] = distances.get(k, float('inf'))
  43.         x = min(unvisited, key=unvisited.get)
  44.  
  45.         dijkstra(graph_in, x, dest, visited, distances, predecessors)
Advertisement
Add Comment
Please, Sign In to add comment