Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def dijkstra(graph_in, src, dest, visited=None, distances=None, predecessors=None) -> list:
- if not predecessors:
- predecessors = {}
- if not distances:
- distances = {}
- if not visited:
- visited = []
- global g_path
- if src not in graph_in:
- raise TypeError("No source in graph")
- if dest not in graph_in:
- raise TypeError("No target in graph")
- if src == dest:
- path = []
- pred = dest
- while pred is not None:
- path.append(pred)
- g_path.append(pred)
- pred = predecessors.get(pred, None)
- g_path = g_path[::-1]
- print("Shortest path: " + str(path[::-1]))
- return path
- else:
- if not visited:
- distances[src] = 0
- for neighbour in graph_in[src]:
- if neighbour not in visited:
- new_distance = distances[src] + graph_in[src][neighbour]
- if new_distance < distances.get(neighbour, float('inf')):
- distances[neighbour] = new_distance
- predecessors[neighbour] = src
- visited.append(src)
- unvisited = {}
- for k in graph_in:
- if k not in visited:
- unvisited[k] = distances.get(k, float('inf'))
- x = min(unvisited, key=unvisited.get)
- dijkstra(graph_in, x, dest, visited, distances, predecessors)
Advertisement
Add Comment
Please, Sign In to add comment