Sei sulla pagina 1di 4

Dijkstra’s Algorithm

Single source shortest path Problem


o This is an example of Dynamic Programming
o This algorithm is used to find the shortest path from a
source vertex v to all other vertices in the graph theory.
o Apply to both directed, undirected and weighted graph,
where weight must be positive.
o Graph must be connected.
Algorithm
dist[s]←0 (distance to source vertex is zero)

for all v ∈ V–{s}


dist[v]←∞ [ set all other distances to infinity ]

S←∅ [ S, the set of visited vertices is initially empty ]


U={V} [ initially U contains all vertices ]
While U≠∅
u ← min-distance(U, dist) [ select the element of U with
minimum distance]

S ← S ∪ {u} [ add u to list of visited vertices ]


for all v ∈ neighbors[u]
do
if dist[v] > dist[u] + w(u,v) [ if new shortest path found ]
then d[v] ←d[u] + w(u,v) [ set new value of shortest
path ]

return dist

Steps
1. Set distance to Source vertex is Zero
2. Set distance to other vertices to infinity (∞)
3. Repeat Steps 4 to 6 Until Unvisited List is Empty
4. Include the vertex with the smallest cost into Visited List
5. Examine its neighboring nodes and calculate its distance to them
6. If the calculated distance is less than currently known distance,
then update the shortest distances for these vertices
Here for above graph,
Visited = { }
Unvisited = { a, b, c, d, e, z }

-- a has shortest distance 0, take it as first visited node


Visited = { a }, Unvisited = { b, c, d, e, z }
-- Find the distance from a to its neighbors i.e. b and c
a to b = 4, a to c to b =3 and a to c =2
Here shortest path = 2, so include c in visited list
Visited ={ a, c} , Unvisited = { b, d, e, z }
- Now find the distance from a, c to its neighboring i.e. b, d and e
a to c to b = 2 +1 = 3, a to c to d = 2 + 8 =10, a to c to e = 2+10 =12
Here shortest path = 3, so include b in visited list.
Visited = { a, c, b }, Unvisited = { d, e, z }
--- Now find the shortest path up to d and e i.e.
a to c to d = 2 + 8 = 10
a to c to b to d = 2 + 1 + 5 = 8
a to c to e = 2 + 10 = 12
Here shortest path = 8, so include d in visited list.
Visited = { a, c, b, d }, Unvisited = { e, z }
-- Now a to c to b to d to e = 8 + 2 = 10 < 12
a to c to b to d to z = 8 + 6 = 14
Here shortest path = 10, include e in visited list.
Visited = { a, c, b, d, e }, Unvisited = { z }
-- Now a to c to b to d to e to z = 13 < 14, include z in visited list.
Visited = { a, c, b, d, e, z }, Unvisited = { }

Vertex Shortest distance Prev Vertex


a 0
b ∞ 4, 3
c ∞ 2
d ∞ 10 9 8
e ∞ 12 10
z ∞ 14 13

Applications of Dijkstra’s Algorithm


i. Algorithms for calculating shortest path from source to sink.
This is useful to calculate the shortest path from one router to
another.
ii. Currency Exchange Problem