Advertisement
skalarr

dijksta sigmund

May 27th, 2022
1,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.37 KB | None | 0 0
  1. function mindist(dist, sptset)
  2.     min = Inf  # Initialize minimum distance for next node
  3.     minindex = 0
  4.     # Search smallest value nearest vertex not in the
  5.     # shortest path tree
  6.     for i in 1:length(G.V)
  7.         if dist[i] < min && sptset[i] == false
  8.             min = dist[i]
  9.             minindex = i
  10.         end
  11.     end
  12.     println("\nNext Node to be processed: ", minindex)
  13.     return minindex
  14. end
  15.  
  16. function dijkstra(G, initial_node)
  17.     println("Source Node:", initial_node)
  18.     println("Graph's Adjacency Matrix:\n", G)
  19.     TreeSet = [false for i in 1:length(G.V) ] # step 1
  20.     dist = [Inf for i in 1:length(G.V) ] # step 2
  21.     dist[initial_node] = 0
  22.  
  23.     for i in 1:length(G.V)
  24.  
  25.         # Pick the minimum distance vertex from
  26.         # the set of vertices not yet processed.
  27.         x = mindist(dist, TreeSet) # step 3
  28.         println("Before relaxation: ", dist)
  29.  
  30.         for j in 1:length(G.V)
  31.             if (G.V[x] > 0 && TreeSet[j] == false && dist[j] > dist[x] + G.V[x])
  32.                 dist[j] = dist[x] + G.V[x]
  33.             end
  34.         end
  35.         println("After relaxation: ", dist)
  36.  
  37.         # Put the minimum distance vertex in the
  38.         # shortest path tree
  39.         TreeSet[x] = true # step 4
  40.     end
  41.  
  42.     println("v | d[v] ")
  43.     println("---------")
  44.     for (i , j) in enumerate(dist)
  45.         println(i, " | ", j)
  46.     end
  47. end
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement