Skip to content

Commit ab23ad1

Browse files
Create dijkstra.cpp
1 parent 8202a15 commit ab23ad1

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

graphs/dijkstra.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <cstdio>
2+
#include <climits>
3+
4+
// Number of vertices in the graph
5+
#define V 9
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+
void printSolution(int dist[], int n)
19+
{
20+
printf("Vertex Distance from Source\n");
21+
for (int i = 0; i < V; i++)
22+
printf("%d tt %d\n", i, dist[i]);
23+
}
24+
25+
void dijkstra(int graph[V][V], int src)
26+
{
27+
int dist[V]; // The output array. dist[i] will hold the shortest
28+
// distance from src to i
29+
30+
bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
31+
// path tree or shortest distance from src to i is finalized
32+
33+
// Initialize all distances as INFINITE and stpSet[] as false
34+
for (int i = 0; i < V; i++)
35+
dist[i] = INT_MAX, sptSet[i] = false;
36+
37+
// Distance of source vertex from itself is always 0
38+
dist[src] = 0;
39+
40+
// Find shortest path for all vertices
41+
for (int count = 0; count < V-1; count++)
42+
{
43+
// Pick the minimum distance vertex from the set of vertices not
44+
// yet processed. u is always equal to src in the first iteration.
45+
int u = minDistance(dist, sptSet);
46+
47+
// Mark the picked vertex as processed
48+
sptSet[u] = true;
49+
50+
// Update dist value of the adjacent vertices of the picked vertex.
51+
for (int v = 0; v < V; v++)
52+
53+
// Update dist[v] only if is not in sptSet, there is an edge from
54+
// u to v, and total weight of path from src to v through u is
55+
// smaller than current value of dist[v]
56+
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
57+
&& dist[u]+graph[u][v] < dist[v])
58+
dist[v] = dist[u] + graph[u][v];
59+
}
60+
printSolution(dist, V);
61+
}
62+
63+
int main()
64+
{
65+
/* Sample graph */
66+
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
67+
{4, 0, 8, 0, 0, 0, 0, 11, 0},
68+
{0, 8, 0, 7, 0, 4, 0, 0, 2},
69+
{0, 0, 7, 0, 9, 14, 0, 0, 0},
70+
{0, 0, 0, 9, 0, 10, 0, 0, 0},
71+
{0, 0, 4, 14, 10, 0, 2, 0, 0},
72+
{0, 0, 0, 0, 0, 2, 0, 1, 6},
73+
{8, 11, 0, 0, 0, 0, 1, 0, 7},
74+
{0, 0, 2, 0, 0, 0, 6, 7, 0}
75+
};
76+
dijkstra(graph, 0);
77+
return 0;
78+
}

0 commit comments

Comments
 (0)