1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
import heapq import math
def init_distance(graph, start): distance = {start: 0} for vertex in graph: if vertex != start: distance[vertex] = math.inf return distance
def dijkstra(graph, start, end):
pqueue = [] heapq.heappush(pqueue, (0, start))
seen = set()
parent = {start: None}
distance = init_distance(graph, start)
while pqueue:
pair = heapq.heappop(pqueue) dist = pair[0] vertex = pair[1]
seen.add(vertex)
nodes = graph[vertex].keys() for node in nodes: if node not in seen: if dist + graph[vertex][node] < distance[node]: heapq.heappush(pqueue, (dist + graph[vertex][node], node)) distance[node] = dist + graph[vertex][node] parent[node] = vertex
path = [end] while parent[path[0]]: path.insert(0, parent[path[0]])
return path, distance[end]
if __name__ == "__main__":
graph = { "A": {"B": 5, "C": 1}, "B": {"A": 5, "C": 2, "D": 1}, "C": {"A": 1, "B": 2, "D": 4, "E": 8}, "D": {"B": 1, "C": 4, "E": 3, "F": 6}, "E": {"C": 8, "D": 3}, "F": {"D": 6} }
path, distance = dijkstra(graph, "A", "F") print(path) print(distance)
|