0

I am currently playing around with the very famous Dijkstra's Algorithm, and am a little stuck. I am trying to modify the pseudo code to take an input of BOTH the source and destination, in efforts to find the SHORTEST path between the two vertices in an implemented Graph. I want to the inputs SOURCE AND DEST to be string values. I am also trying to modify, so the input is simply the list SHORTEST PATH. Any ideas on how I can modify the algorithm to obtain this?

1:  function Dijkstra(Graph, source):
2:  for each vertex v in Graph: // Initialization
3:  dist[v] := infinity // initial distance from source to vertex v is set to infinite
4:  previous[v] := undefined    // Previous node in optimal path from source
5:  dist[source] := 0   // Distance from source to source
6:  Q := the set of all nodes in Graph  // all nodes in the graph are unoptimized - thus are in Q
7:  while Q is not empty:   // main loop
8:  u := node in Q with smallest dist[ ]
9:  remove u from Q
10: for each neighbor v of u:   // where v has not yet been removed from Q.
11: alt := dist[u] + dist_between(u, v)
12: if alt < dist[v]    // Relax (u,v)
13: dist[v] := alt
14: previous[v] := u
15: return previous[ ]

1 Answers1

0

Simple, add DESTINATION as an argument that your function accepts as input and continue the algorithm as usual. Just remove the last line

return previous[ ]

And add the following lines which accesses the previous[] list only for the nodes in the shortest path. You start this traversal from the DEST node and go till you reach SOURCE

x := DEST
shortest_path := []
while x is not equal to SOURCE:
       shortest_path.add(x)
       x := previous[x]
 shortest_path.add(x) //finally add the SOURCE outside the loop
 return shortest_path[]

To take SOURCE and DEST as string values, you need a routine which takes a string and returns a Node that is in that Graph with the value given by the input string.

Algorithm getNodeFromString(Graph G, String s):
      for every node N in G:
             if N.id == s:
                   return N

This is, of course, assuming that every node in Graph has a unique identifier.

Tejash Desai
  • 466
  • 4
  • 11