AndreiS

Untitled

Apr 19th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. int minDistance(int n, int dist[], bool sptSet[])
  2. {
  3. // Initialize min value
  4. int min = INT_MAX, min_index;
  5.  
  6. for (int v = 0; v < n; v++)
  7. if (sptSet[v] == false && dist[v] <= min)
  8. min = dist[v], min_index = v;
  9.  
  10. return min_index;
  11. }
  12.  
  13. void printSolution(int dist[],int nextHop[], int n)
  14. {
  15. printf("Vertex Distance from Source nextHop\n");
  16. for (int i = 0; i < n; i++)
  17. printf("%d \t\t %d \t\t %d\n", i, dist[i], nextHop[i]);
  18. }
  19.  
  20. void dijkstra(int n, int **graph, int src)
  21. {
  22. int dist[n]; // The output array. dist[i] will hold the shortest
  23. // distance from src to i
  24.  
  25. bool sptSet[n]; // sptSet[i] will true if vertex i is included in shortest
  26. // path tree or shortest distance from src to i is finalized
  27.  
  28. int nextHop[n];
  29.  
  30. // Initialize all distances as INFINITE and stpSet[] as false
  31. for (int i = 0; i < n; i++)
  32. dist[i] = INT_MAX, sptSet[i] = false;
  33.  
  34. // Distance of source vertex from itself is always 0
  35. dist[src] = 0;
  36.  
  37. // Find shortest path for all vertices
  38. for (int count = 0; count < n-1; count++)
  39. {
  40. // Pick the minimum distance vertex from the set of vertices not
  41. // yet processed. u is always equal to src in first iteration.
  42. int u = minDistance(n, dist, sptSet);
  43.  
  44. // Mark the picked vertex as processed
  45. sptSet[u] = true;
  46.  
  47. // Update dist value of the adjacent vertices of the picked vertex.
  48.  
  49. for (int v = 0; v < n; v++)
  50.  
  51. // Update dist[v] only if is not in sptSet, there is an edge from
  52. // u to v, and total weight of path from src to v through u is
  53. // smaller than current value of dist[v]
  54. if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
  55. && dist[u]+graph[u][v] < dist[v]){
  56. dist[v] = dist[u] + graph[u][v];
  57. nextHop[v] = u;
  58. };
  59. }
  60.  
  61. // print the constructed distance array
  62. printSolution(dist,nextHop, n);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment