Dijkstra's algorithm with python
Pseudocode
In the following algorithm, the code
u := vertex in Q with smallest dist[], searches for the vertexuin the vertex setQthat has the leastdist[u]value. That vertex is removed from the setQand returned to the user.dist_between(u, v)calculates the length between the two neighbor-nodesuandv. The variablealton line 15 is the length of the path from the root node to the neighbor nodevif it were to go throughu. If this path is shorter than the current shortest path recorded forv, that current path is replaced with thisaltpath. Thepreviousarray is populated with a pointer to the "next-hop" node on the source graph to get the shortest route to the source.1 function Dijkstra(Graph, source): 2 for each vertex v in Graph: // Initializations 3 dist[v] := infinity ; // Unknown distance function from source to v 4 previous[v] := undefined ; // Previous node in optimal path from source 5 end for ; 6 dist[source] := 0 ; // Distance from source to source 7 Q := the set of all nodes in Graph ; // All nodes in the graph are unoptimized - thus are in Q 8 while Q is not empty: // The main loop 9 u := vertex in Q with smallest dist[] ; 10 if dist[u] = infinity: 11 break ; // all remaining vertices are inaccessible from source 12 end if ; 13 remove u from Q ; 14 for each neighbor v of u: // where v has not yet been removed from Q. 15 alt := dist[u] + dist_between(u, v) ; 16 if alt < dist[v]: // Relax (u,v,a) 17 dist[v] := alt ; 18 previous[v] := u ; 19 decrease-key v in Q; // Reorder v in the Queue 20 end if ; 21 end for ; 22 end while ; 23 return dist[] ; 24 end Dijkstra.If we are only interested in a shortest path between vertices
sourceandtarget, we can terminate the search at line 13 ifu = target. Now we can read the shortest path fromsourcetotargetby iteration:1 S := empty sequence 2 u := target 3 while previous[u] is defined: 4 insert u at the beginning of S 5 u := previous[u]
dijkstra
nodeNum = 3;
source = 2;
dist = [ 10000 for i in range(nodeNum) ];
dist[source-1] = 0;
outNodeList = [ 0 for i in range(nodeNum) ];
pre = [ -1 for i in range(nodeNum) ];
Q = range(nodeNum);
edgeFile = open('drg.data', 'r');
for line in edgeFile :
line = line.strip('\n');
[frm, to, wei] = line.split("\t");
outNodeList[frm-1] = [to-1, wei];
edgeFile.close();
while len(Q) > 0 :
minDist = dist[Q[0]];
minIdx = 0;
for i in range(1, len(Q)):
if dist[Q[i]] < minDist :
minIdx = i;
if dist[minIdx] == 10000 :
break;
del Q[minIdx]; # delete min node
outNodeList = outNode[minIdx];
for i in range(len(outNodeList)):
[neibor, wei] = outNodeList[i];
if dist[minIdx] + wei < dist[neibor] :
dist[neibor] = dist[minIdx] + wei;
pre[neibor] = minIdx;
for i in range(nodeNum):
print(i, dist[i]);
浙公网安备 33010602011771号