ronith
10/8/2018 - 6:23 AM

## Dijkstra’s Algorithm for Adjacency Matrix representation

Algorithm

1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty.
2. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3. While sptSet doesn’t include all vertices ….a) Pick a vertex u which is not there in sptSet and has minimum distance value. ….b) Include u to sptSet. ….c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v.
``````//https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
#include<iostream>
using namespace std;
#define v 9

int minDist (int dist[], bool spset[]) {
int minIndex, min=INT_MAX;
for (int i=0; i<v; i++)
if (spset[i]== 0 && dist[i]<= min)
min=dist[i],minIndex= i;
return minIndex;
}
void dijkstra (int graph[][v], int s) {
bool spset[v]= {0};
int dist[v];
for (int i=0; i<v;i++)
dist[i]= INT_MAX;
dist[s]= 0;

for (int c=0; c<v-1; c++) {
int u= minDist(dist, spset);

spset[u]= 1;
for (int i=0;i<v; i++)
if (!spset[i] && graph[u][i]!=0 && dist[u]!= INT_MAX && dist[i]>dist[u]+graph[u][i])
dist[i]= dist[u]+graph[u][i];
}
for (int i=0;i<v;i++)
(dist[i]==INT_MAX)?cout<<i<< "\tInf\n":cout<<i<< "\t"<< dist[i]<<"\n";

}

int main() {
int graph[v][v] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};

dijkstra(graph, 0);
}
``````