Induction:
Dijkstra’s algorithm is an algorithm for finding the shortest paths between
nodes in a graph, which may represent, for example, road networks. It was conce
ived by computer scientist Edsger W. Dijkstra in 1956 and published three years
later.
Dijkstra’s algorithm
Dijkstra’s algorithm finds a shortest path tree from a single source node, by
building a set of nodes that have minimum distance from the source.
The graph has the following:
-
vertices, or nodes, denoted in the algorithm by v or u;
-
weighted edges that connect two nodes: (u, v) denotean edge, and w(u,v)
denotes its weight.
This is done by initializing three values:
-
dist, an array of distances from the source node s to each node in
the graph, initialized the following way: dist(s) = 0; and for all oth
er nodes v, dist(v) = ∞infty∞. This is done at the beginning because
as the algorithm proceeds, the dist from the source to each node v in
the graph will be recalculated and finalized when the shortest distance to
v is found. -
Q, a queue of all nodes in the graph. At the end of the algorithm’s
progress, Q will be empty. -
S, an empty set, to indicate which nodes the algorithm has visited.
At the end of the algorithm’s run, S will contain all the nodes of
the graph.
The algorithm proceeds as follows:
-
While Q is not empty, pop the node v, that is not already in S,
from Q with the smallest dist(v). In the first run, source node s
will be chosen because dist(s) was initialized to 0. In the next run,
the next node with the smallest dist value is chosen. -
Add node v to S, to indicate that v has been visited.
-
Update dist values of adjacent nodes of the current node v as follows:
for each new adjacent node u,-
if dist(v) + weight(u,v) < dist(u), there is a new minimal distance
found for u, so update dist(u) to the new minimal distance value; -
otherwise, no updates are made to dist(u).
-
The algorithm has visited all nodes in the graph and found the smallest distance
to each node. distdistdist now contains the shortest path tree from source s.
==Note: The weight of an edge(u, v) is taken from the value associated with (u, v)
on the graph.==
Implmentation:
This is pseudocode for Dijkstra’s algorithm, mirroring Python syntax. It can be used in order to implement the algorithm in any language.
1 |
function Dijkstra(Graph, source): |
This is the python code for the dijkstra algorithm.
1 |
import heapq |
近期评论