|
| 1 | +// A C++ program for Dijkstra's single source shortest path algorithm. |
| 2 | +// The program is for adjacency matrix representation of the graph . |
| 3 | + |
| 4 | +#include <limits.h> |
| 5 | +#include <stdio.h> |
| 6 | + |
| 7 | +#define V 9 |
| 8 | + |
| 9 | +int minDistance(int dist[], bool sptSet[]) |
| 10 | +{ |
| 11 | + |
| 12 | +int min = INT_MAX, min_index; |
| 13 | + |
| 14 | +for (int v = 0; v < V; v++) |
| 15 | +if (sptSet[v] == false && dist[v] <= min) |
| 16 | +min = dist[v], min_index = v; |
| 17 | + |
| 18 | +return min_index; |
| 19 | +} |
| 20 | + |
| 21 | +void printSolution(int dist[]) |
| 22 | +{ |
| 23 | +printf("Vertex \t\t Distance from Source\n"); |
| 24 | +for (int i = 0; i < V; i++) |
| 25 | +printf("%d \t\t %d\n", i, dist[i]); |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +void dijkstra(int graph[V][V], int src) |
| 30 | +{ |
| 31 | +int dist[V]; |
| 32 | + |
| 33 | + |
| 34 | +bool sptSet[V]; |
| 35 | + |
| 36 | +for (int i = 0; i < V; i++) |
| 37 | +dist[i] = INT_MAX, sptSet[i] = false; |
| 38 | + |
| 39 | + |
| 40 | +dist[src] = 0; |
| 41 | + |
| 42 | + |
| 43 | +for (int count = 0; count < V - 1; count++) { |
| 44 | + |
| 45 | +int u = minDistance(dist, sptSet); |
| 46 | + |
| 47 | +sptSet[u] = true; |
| 48 | + |
| 49 | + |
| 50 | +for (int v = 0; v < V; v++) |
| 51 | + |
| 52 | +if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX |
| 53 | +&& dist[u] + graph[u][v] < dist[v]) |
| 54 | +dist[v] = dist[u] + graph[u][v]; |
| 55 | +} |
| 56 | + |
| 57 | +printSolution(dist); |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +int main() |
| 62 | +{ |
| 63 | + |
| 64 | +int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, |
| 65 | +{ 4, 0, 8, 0, 0, 0, 0, 11, 0 }, |
| 66 | +{ 0, 8, 0, 7, 0, 4, 0, 0, 2 }, |
| 67 | +{ 0, 0, 7, 0, 9, 14, 0, 0, 0 }, |
| 68 | +{ 0, 0, 0, 9, 0, 10, 0, 0, 0 }, |
| 69 | +{ 0, 0, 4, 14, 10, 0, 2, 0, 0 }, |
| 70 | +{ 0, 0, 0, 0, 0, 2, 0, 1, 6 }, |
| 71 | +{ 8, 11, 0, 0, 0, 0, 1, 0, 7 }, |
| 72 | +{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; |
| 73 | + |
| 74 | +dijkstra(graph, 0); |
| 75 | + |
| 76 | +return 0; |
| 77 | +} |
0 commit comments