Advertisement
minh_tran_782

Dijstra Algo

Nov 13th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. // Some helping functions
  2. int minDistance(int dist[], bool sptSet[], int size)
  3. {
  4.  
  5.     // Initialize min value
  6.     int min = INT_MAX, min_index;
  7.  
  8.     for (int v = 0; v < size; v++)
  9.         if (sptSet[v] == false && dist[v] <= min)
  10.             min = dist[v], min_index = v;
  11.  
  12.     return min_index;
  13. }
  14. int Dijkstra(int** graph, int src, int dst) {
  15.  int size = *(&graph[0] + 1) - graph[0];
  16.     int* dist = new int[size]; // The output array. dist[i] will hold the shortest
  17.     // distance from src to i
  18.  
  19.     bool* sptSet = new bool[size]; // sptSet[i] will be true if vertex i is included in shortest
  20.     // path tree or shortest distance from src to i is finalized
  21.  
  22.     // Initialize all distances as INFINITE and stpSet[] as false
  23.     for (int i = 0; i < size; i++)
  24.         dist[i] = INT_MAX, sptSet[i] = false;
  25.  
  26.     // Distance of source vertex from itself is always 0
  27.     dist[src] = 0;
  28.  
  29.     // Find shortest path for all vertices
  30.     for (int count = 0; count < size - 1; count++) {
  31.         // Pick the minimum distance vertex from the set of vertices not
  32.         // yet processed. u is always equal to src in the first iteration.
  33.         int u = minDistance(dist, sptSet,size);
  34.  
  35.         // Mark the picked vertex as processed
  36.         sptSet[u] = true;
  37.  
  38.         // Update dist value of the adjacent vertices of the picked vertex.
  39.         for (int v = 0; v < size; v++)
  40.  
  41.             // Update dist[v] only if is not in sptSet, there is an edge from
  42.             // u to v, and total weight of path from src to v through u is
  43.             // smaller than current value of dist[v]
  44.             if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
  45.                 && dist[u] + graph[u][v] < dist[v])
  46.                 dist[v] = dist[u] + graph[u][v];
  47.     }
  48.     int res = dist[dst];
  49.     delete[] sptSet;
  50.     delete[] dist;
  51.     return res;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement