Dijkstra Algorithm
Dijkstra Algorithm
Output: 0 4 12 19 21 11 9 8 14
Explanation: The distance from 0 to 1 = 4.
The minimum distance from 0 to 2 = 12. 0->1->2
The minimum distance from 0 to 3 = 19. 0->1->2->3
The minimum distance from 0 to 4 = 21. 0->7->6->5->4
The minimum distance from 0 to 5 = 11. 0->7->6->5
The minimum distance from 0 to 6 = 9. 0->7->6
The minimum distance from 0 to 7 = 8. 0->7
The minimum distance from 0 to 8 = 14. 0->1->2->8
Step 2:
Pick the vertex with minimum distance value and not
already included in SPT (not in sptSET ). The vertex 1 is
picked and added to sptSet .
So sptSet now becomes {0, 1}. Update the distance
values of adjacent vertices of 1.
The distance value of vertex 2 becomes 12
Step 3:
Pick the vertex with minimum distance value and not
already included in SPT (not in sptSET ). Vertex 7 is
picked. So sptSet now becomes {0, 1, 7}.
Update the distance values of adjacent vertices of 7. The
distance value of vertex 6 and 8 becomes finite ( 15 and
9 respectively).
Step 4:
Pick the vertex with minimum distance value and not
already included in SPT (not in sptSET ). Vertex 6 is
picked. So sptSet now becomes {0, 1, 7, 6} .
Update the distance values of adjacent vertices of 6. The
distance value of vertex 5 and 8 are updated.
We repeat the above steps until sptSet includes all vertices of the
given graph. Finally, we get the following S hortest Path Tree
(SPT).
Program:
/* C++ program for Dijkstra's single source shortest path
algorithm. The program is for adjacency matrix representation
of the graph*/
#include <iostream>
using namespace std;
#include <limits.h>
// Number of vertices in the graph
#define V 9
/* A utility function to find the vertex with minimum distance
value, from the set of vertices not yet included in shortest path
tree*/
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// A utility function to print the constructed distance array
void printSolution(int dist[])
{
cout << "Vertex \t Distance from Source" << endl;
for (int i = 0; i < V; i++)
cout << i << " \t\t\t\t" << dist[i] << endl;
}