Dijsktra's Algorithm

AIM: To implementation Dijkstra's algorithm to find shortest path in the graph.
SOURCE CODE:
#include<iostream>
#include <limits.h>
using namespace std;
int minDistance(int dist[], bool sptSet[],int V)
{
    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;
}
int printSolution(int dist[], int V)
{
    cout<<"Vertex\t\tDistance from Source"<<endl;
    for (int i = 0; i < V; i++)
    cout<<"\t"<<i<<"\t\t"<<dist[i]<<endl;
  return 0;
}
void dijkstra(int graph[20][20], int src,int V)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V-1; count++)
{
    int u = minDistance(dist, sptSet,V);
    sptSet[u] = true;
        for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main()
{
    int graph[20][20],V,i,j;
    cout<<"Enter number of vertices:"<<endl;
    cin>>V;
    cout<<"Enter weights of each edge between two vertices:"<<endl;
    for(i=0;i<V;i++)
        for(j=0;j<V;j++)
            cin>>graph[i][j];
    dijkstra(graph, 0,V);
    return 0;
}
OUTPUT:
Enter number of vertices:5
Enter weights of each edge between two vertices:
0 2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
Vertex Distance from Source
0 0
1 2
2 5
3 6
4 7

No comments:

Post a Comment

Total Pageviews