Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int minDistance(int n, int dist[], bool sptSet[])
- {
- // Initialize min value
- int min = INT_MAX, min_index;
- for (int v = 0; v < n; v++)
- if (sptSet[v] == false && dist[v] <= min)
- min = dist[v], min_index = v;
- return min_index;
- }
- void printSolution(int dist[],int nextHop[], int n)
- {
- printf("Vertex Distance from Source nextHop\n");
- for (int i = 0; i < n; i++)
- printf("%d \t\t %d \t\t %d\n", i, dist[i], nextHop[i]);
- }
- void dijkstra(int n, int **graph, int src)
- {
- int dist[n]; // The output array. dist[i] will hold the shortest
- // distance from src to i
- bool sptSet[n]; // sptSet[i] will true if vertex i is included in shortest
- // path tree or shortest distance from src to i is finalized
- int nextHop[n];
- // Initialize all distances as INFINITE and stpSet[] as false
- for (int i = 0; i < n; i++)
- dist[i] = INT_MAX, sptSet[i] = false;
- // Distance of source vertex from itself is always 0
- dist[src] = 0;
- // Find shortest path for all vertices
- for (int count = 0; count < n-1; count++)
- {
- // Pick the minimum distance vertex from the set of vertices not
- // yet processed. u is always equal to src in first iteration.
- int u = minDistance(n, dist, sptSet);
- // Mark the picked vertex as processed
- sptSet[u] = true;
- // Update dist value of the adjacent vertices of the picked vertex.
- for (int v = 0; v < n; v++)
- // Update dist[v] only if is not in sptSet, there is an edge from
- // u to v, and total weight of path from src to v through u is
- // smaller than current value of dist[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];
- nextHop[v] = u;
- };
- }
- // print the constructed distance array
- printSolution(dist,nextHop, n);
- }
Advertisement
Add Comment
Please, Sign In to add comment