2. INTRODUCTION
Dijkstra’s algorithm calculates the least distance
from a starting vertex to a destination vertex from
the given weighted graph
Input:
• A weighted graph
• Starting vertex
• Destination vertex
Output:
A graph which connects all the vertices with least
distance
3. Dijkstra's Algorithm
Input:
a weighted digraph G=(V,E) with positive edge weights
a source node s V∈
Initialization:
d[s]=0
for each vertex x V-s∈
d[x]=infinity
Mark all the vertices as unprocessed
Iteration:
for i=1 to |V|
Choose an unprocessed vertex x from V with minimum d[x]
Mark x as processed
for all y adj(x)∈
if d[y] > d[x]+w(x,y)
d[y] = d[x]+w(x,y)
4. Dijkstra's Algorithm With PATH
Input:
a weighted digraph G=(V,E) with positive edge weights
a source node s V∈
Initialization:
d[s]=0 predecessor [ s ] = undefined
for each vertex x V-s∈
d[x]=infinity
Mark all the vertices as unprocessed
Iteration:
for i=1 to |V|
Choose an unprocessed vertex x from V with minimum d[x]
Mark x as processed
for all y adj(x)∈
if d[y] > d[x]+w(x,y)
d[y] = d[x]+w(x,y)
predecessor [ y ] = x
5. Printing the Distance and path
for each vertex v
{
print Distance d[v]
print_path(v);
}
print_path(v)
{
if (v is undefined)
return;
else
print_path ( prdecessor[v] ); // note recursion
print v
}
6. C Code
for(i=1; i<=numofvertices; i++)
{
printf("nDistance : %d ::: Path: ",distance[i]);
print_path(i);
}
void print_path(int i)
{
if (i==-1)
return;
else
print_path(prdecessor[i]);
Assumes that vertices are
numbered from 1.
distance array and
predecessor array are
computed by dijkstra
algorithm
-1 is undefined vertex
7. Dijkstra's Shortest Path Algorithm
Find shortest path from s to t.
7
s
3
t
2
6
7
4
5
24
18
2
9
14
15
5
30
20
44
16
11
6
19
6