|  | 
|  | 1 | +#include <limits.h>  | 
|  | 2 | +#include <stdio.h>  | 
|  | 3 | + | 
|  | 4 | +#define V 9  | 
|  | 5 | + | 
|  | 6 | +int minDistance(int dist[], bool sptSet[]) | 
|  | 7 | +{ | 
|  | 8 | +// Initialize min value  | 
|  | 9 | +int min = INT_MAX, min_index; | 
|  | 10 | + | 
|  | 11 | +for (int v = 0; v < V; v++) | 
|  | 12 | +if (sptSet[v] == false && dist[v] <= min) | 
|  | 13 | +min = dist[v], min_index = v; | 
|  | 14 | + | 
|  | 15 | +return min_index; | 
|  | 16 | +} | 
|  | 17 | + | 
|  | 18 | +// A utility function to print the constructed distance array  | 
|  | 19 | +int printSolution(int dist[], int n) | 
|  | 20 | +{ | 
|  | 21 | +printf("Vertex Distance from Source\n"); | 
|  | 22 | +for (int i = 0; i < V; i++) | 
|  | 23 | +printf("%d tt %d\n", i, dist[i]); | 
|  | 24 | +} | 
|  | 25 | + | 
|  | 26 | + | 
|  | 27 | +void dijkstra(int graph[V][V], int src) | 
|  | 28 | +{ | 
|  | 29 | +int dist[V]; | 
|  | 30 | +bool sptSet[V]; | 
|  | 31 | +for (int i = 0; i < V; i++) | 
|  | 32 | +dist[i] = INT_MAX, sptSet[i] = false; | 
|  | 33 | + | 
|  | 34 | +dist[src] = 0; | 
|  | 35 | + | 
|  | 36 | +for (int count = 0; count < V - 1; count++) { | 
|  | 37 | + | 
|  | 38 | +int u = minDistance(dist, sptSet); | 
|  | 39 | + | 
|  | 40 | +// Mark the picked vertex as processed  | 
|  | 41 | +sptSet[u] = true; | 
|  | 42 | + | 
|  | 43 | +// Update dist value of the adjacent vertices of the picked vertex.  | 
|  | 44 | +for (int v = 0; v < V; v++) | 
|  | 45 | +if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX | 
|  | 46 | +&& dist[u] + graph[u][v] < dist[v]) | 
|  | 47 | +dist[v] = dist[u] + graph[u][v]; | 
|  | 48 | +} | 
|  | 49 | + | 
|  | 50 | +printSolution(dist, V); | 
|  | 51 | +} | 
|  | 52 | + | 
|  | 53 | +// driver program to test above function  | 
|  | 54 | +int main() | 
|  | 55 | +{ | 
|  | 56 | + | 
|  | 57 | +int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, | 
|  | 58 | +{ 4, 0, 8, 0, 0, 0, 0, 11, 0 }, | 
|  | 59 | +{ 0, 8, 0, 7, 0, 4, 0, 0, 2 }, | 
|  | 60 | +{ 0, 0, 7, 0, 9, 14, 0, 0, 0 }, | 
|  | 61 | +{ 0, 0, 0, 9, 0, 10, 0, 0, 0 }, | 
|  | 62 | +{ 0, 0, 4, 14, 10, 0, 2, 0, 0 }, | 
|  | 63 | +{ 0, 0, 0, 0, 0, 2, 0, 1, 6 }, | 
|  | 64 | +{ 8, 11, 0, 0, 0, 0, 1, 0, 7 }, | 
|  | 65 | +{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; | 
|  | 66 | + | 
|  | 67 | +dijkstra(graph, 0); | 
|  | 68 | + | 
|  | 69 | +return 0; | 
|  | 70 | +} | 
0 commit comments