1 #Dijkstra algorithm--Relaxation by edges2 #specify a path to a point to each of the other vertices--single source Shortest path3 4 #Initialization diagram Parameters5G = {1:{1:0, 2:1, 3:12},62:{2:0, 3:9, 4:3},73:{3:0, 5:5},84:{3:4, 4:0, 5:13, 6:15},95:{5:0, 6:4},Ten6:{6: 0}} One A - #each time a vertex closest to the source point is found, then the center of gravity for the vertex expands - #The shortest path to the source point to all remaining points the #a greedy algorithm - - defDijkstra (g,v0,inf=999): - """calculates the distance from a specified point v0 to the shortest path of any point in figure G using the Dijkstra algorithm + INF is a set infinite distance value - This method does not solve the graph of negative weight edges + """ ABook =set () atMINV =V0 - - #The initial distance from the source vertex to the remaining vertices -dis = Dict ((k,inf) forKinchG.keys ()) -Dis[v0] =0 - in whileLen (book) <Len (G): -Book.add (MINV)#determine the distance from the current vertex to forWinchG[MINV]:#spread out at the center of the current point + ifDIS[MINV] + g[minv][w] < Dis[w]:#if the distance from the current point to a point is small and the shortest distance known -DIS[W] = Dis[minv] + g[minv][w]#update a known distance the *New = INF#Select the minimum distance point from the remaining indeterminate points as the new diffusion point $ forVinchDis.keys ():Panax Notoginseng ifVinchBookContinue - ifDIS[V] <NEW: theNew =Dis[v] +MINV =v A returnDis the + -dis = Dijkstra (g,v0=1) $ PrintDis.values ()
Python data structure and algorithm--the shortest path of graphs (Dijkstra algorithm)