Maharaja Institute of Technology Mysore Department of Information Science and Engineering
for j←1 to n - 1 //find n - 1 edges
Let vi ϵ Y be such that C[vi] is minimum
T ← T U {( vi, N[vi])} //add edge (vi, N[vi]) to T
X ← X U {vi} //add vertex vi to X
Y ← Y – {vi} //delete vertex vi from Y
for each vertex w ϵ Y that is adjacent to vi
if Length[vi,w] < C[w] then
N[w] ← vi
C[w] ← Length[vi,w]
end if
end for
end for
Analysis
3.6 Single source shortest paths
Design and Analysis of Algorithms (18CS42), Module III. Greedy Technique Page | 1
Maharaja Institute of Technology Mysore Department of Information Science and Engineering
3.6.1 Dijkstra's Algorithm
Design and Analysis of Algorithms (18CS42), Module III. Greedy Technique Page | 2
Maharaja Institute of Technology Mysore Department of Information Science and Engineering
ALGORITHM: Dijkstra( )
//Input: A weighted directed graph G = (V,E), where V = {v1,v2, ,vn}.
//Output: The distance from vertex 1 to every other vertex in G.
Design and Analysis of Algorithms (18CS42), Module III. Greedy Technique Page | 3
Maharaja Institute of Technology Mysore Department of Information Science and Engineering
X = {v1}; // X-visited vertices
Y ← V - {v1}; // Y-unvisited vertices
cost[v1]← 0; // source to source vertices cost is zero
for i←2 to n
if vi is adjacent to v1 then
cost[vi] ← length[v1, vi] //from source v1 to vi
else
cost[vi] ← ∞ //999 or infinite
end if
end for
for j←1 to n-1
Let vi ϵ Y be such that cost[vi] is minimum
X ← X U {vi} //add vertex vi to X
Y ← Y – {vi} //delete vertex vi from Y
for each edge (vi,w)
if vi ϵ Y and cost[vi] + length[vi,w] < cost[w] then
cost[w] ← cost[vi] + length[vi,w]
end for
end for
Analysis:
Time Complexity of Dijkstra's Algorithm is Ꝋ(V2)
3.7 Optimal Tree Problem
Design and Analysis of Algorithms (18CS42), Module III. Greedy Technique Page | 4