# C++ Program to Implement Dijkstra’s Algorithm using Set

«
»
This is a C++ Program to find shortest path. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has minimum distance from source.
Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph.
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 sptSetand 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.

Here is source code of the C++ Program to Implement Dijkstra’s Algorithm Using Set. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

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 <stdio.h>`
5. `#include <limits.h>`
6. ` `
7. `// Number of vertices in the graph`
8. `#define V 9`
9. ` `
10. `// A utility function to find the vertex with minimum distance value, from`
11. `// the set of vertices not yet included in shortest path tree`
12. `int minDistance(int dist[], bool sptSet[])`
13. `{`
14. `    // Initialize min value`
15. `    int min = INT_MAX, min_index;`
16. ` `
17. `    for (int v = 0; v < V; v++)`
18. `        if (sptSet[v] == false && dist[v] <= min)`
19. `            min = dist[v], min_index = v;`
20. ` `
21. `    return min_index;`
22. `}`
23. ` `
24. `// A utility function to print the constructed distance array`
25. `int printSolution(int dist[], int n)`
26. `{`
27. `    printf("Vertex   Distance from Source\n");`
28. `    for (int i = 0; i < V; i++)`
29. `        printf("%d \t\t %d\n", i, dist[i]);`
30. `}`
31. ` `
32. `// Funtion that implements Dijkstra's single source shortest path algorithm`
33. `// for a graph represented using adjacency matrix representation`
34. `void dijkstra(int graph[V][V], int src)`
35. `{`
36. `    int dist[V]; // The output array.  dist[i] will hold the shortest`
37. `    // distance from src to i`
38. ` `
39. `    bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest`
40. `    // path tree or shortest distance from src to i is finalized`
41. ` `
42. `    // Initialize all distances as INFINITE and stpSet[] as false`
43. `    for (int i = 0; i < V; i++)`
44. `        dist[i] = INT_MAX, sptSet[i] = false;`
45. ` `
46. `    // Distance of source vertex from itself is always 0`
47. `    dist[src] = 0;`
48. ` `
49. `    // Find shortest path for all vertices`
50. `    for (int count = 0; count < V - 1; count++)`
51. `    {`
52. `        // Pick the minimum distance vertex from the set of vertices not`
53. `        // yet processed. u is always equal to src in first iteration.`
54. `        int u = minDistance(dist, sptSet);`
55. ` `
56. `        // Mark the picked vertex as processed`
57. `        sptSet[u] = true;`
58. ` `
59. `        // Update dist value of the adjacent vertices of the picked vertex.`
60. `        for (int v = 0; v < V; v++)`
61. ` `
62. `            // Update dist[v] only if is not in sptSet, there is an edge from`
63. `            // u to v, and total weight of path from src to  v through u is`
64. `            // smaller than current value of dist[v]`
65. `            if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]`
66. `                    + graph[u][v] < dist[v])`
67. `                dist[v] = dist[u] + graph[u][v];`
68. `    }`
69. ` `
70. `    // print the constructed distance array`
71. `    printSolution(dist, V);`
72. `}`
73. ` `
74. `// driver program to test above function`
75. `int main()`
76. `{`
77. `    /* Let us create the example graph discussed above */`
78. `    int graph[V][V] =`
79. `            { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, {`
80. `                    0, 8, 0, 7, 0, 4, 0, 0, 2 },`
81. `                    { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0,`
82. `                            0 }, { 0, 0, 4, 0, 10, 0, 2, 0, 0 }, { 0, 0, 0, 14,`
83. `                            0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, {`
84. `                            0, 0, 2, 0, 0, 0, 6, 7, 0 } };`
85. ` `
86. `    dijkstra(graph, 0);`
87. ` `
88. `    return 0;`
89. `}`

Output:

```\$ g++ DijkstraUsingSet.cpp
\$ a.out

Vertex   Distance from Source
0 		 0
1 		 4
2 		 12
3 		 19
4 		 21
5 		 11
6 		 9
7 		 8
8 		 14
------------------
(program exited with code: 0)

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube 