1

Hi I am trying to find an minimum possible route in my weighted graph using Dijkstra'a algorithm. I am trying to implement the algorithm below from geeksforgeeks.com :

1) Initialize distances of all vertices as infinite.

2) Create an empty priority_queue pq.  Every item
   of pq is a pair (weight, vertex). Weight (or 
   distance) is used used as first item  of pair
   as first item is by default used to compare
   two pairs

3) Insert source vertex into pq and make its
   distance as 0.

4) While either pq doesn't become empty
    a) Extract minimum distance vertex from pq. 
       Let the extracted vertex be u.
    b) Loop through all adjacent of u and do 
       following for every vertex v.

           // If there is a shorter path to v
           // through u. 
           If dist[v] > dist[u] + weight(u, v)

               (i) Update distance of v, i.e., do
                     dist[v] = dist[u] + weight(u, v)
               (ii) Insert v into the pq (Even if v is
                    already there)

5) Print distance array dist[] to print all shortest
   paths. 

My main Data Structures are:

 // HashMap of Intersections 
    private static HashMap<String, Intersection> intersections;
    // Edge/Rail List
    private static ArrayList<Rail> railList;

My function below called route and it first gets source and destination vertexes from the commands as String and then i try to implement algorithm above. However i do not know how to store them in final Arraylist so that i can return the path.Additionally, it is problematic i think:

public void route(String wholeLine){
        String[] temp = wholeLine.split(" |\\>");
        int vel = Integer.parseInt(temp[3]);
        double totalpath = 0;
        int numOfSwitches = 0;
        // My Source and Destination Nodes
        Intersection src = intersections.get(temp[1]);
        Intersection dest = intersections.get(temp[2]);
        // Start the operation
        PriorityQueue<Intersection> pq = new PriorityQueue<RailNetwork.Intersection>();
        // Setting Distance to 0 for Source Node
        src.setDistanceFromSource(0);
        pq.add(src);
        // While Priority Queue not empty
        while(pq.size() != 0){
            // Extract the vertex with minimum distance value node from Min Heap. Let the extracted vertex be u.
            Intersection u = pq.remove();
            // For every adjacent vertex v of u, check if v is in Min Heap. 

            for(Intersection v : u.getNeigbours()){
                double weight = 0;
                // Find edgeweight of u and v from rail/edge list
                for(int i = 0;i<railList.size();i++){
                    if(railList.get(i).getSrc().getLabel().equals(u.label) && railList.get(i).getDest().getLabel().equals(v.label)){
                        weight = railList.get(i).getDistance();
                    }
                    else if(railList.get(i).getSrc().getLabel().equals(v.label) && railList.get(i).getDest().getLabel().equals(u.label)){
                        weight = railList.get(i).getDistance();
                    }
                }
                //If v is in Min Heap and distance value is more than weight of u-v plus distance value of u, then update the distance value of v.
                if(u.getDistanceFromSource() > v.getDistanceFromSource() + weight){
                    //Update distance of v, i.e., do dist[v] = dist[u] + weight(u, v)
                    v.setDistanceFromSource(u.getDistanceFromSource() + weight);
                    System.out.println(v.label + "\t" + v.distanceFromSource);
                    pq.add(v);
                }
            }

        }
    }

**Could someone please help me to find my mistakes in order to implement it correctly?**Any help or hint is appreciated. Thanks in advance stackoverflow family.

Habil96
  • 75
  • 1
  • 10
  • Why do you want to store it in an `ArrayList`? Why not return a `Collection` and just return the `pq` instance? Otherwise, just return `new ArrayList<>(pq)`. – M. le Rutte May 13 '18 at 11:34
  • @M.leRutte You don't want to return `pq`, it's empty at the end of Dijkstra's. – k_ssb May 13 '18 at 11:35
  • Ah, I don't know the algorithm. I see that there is a `remove` in the code. – M. le Rutte May 13 '18 at 11:36
  • (1. [Fibonacci heap](https://en.wikipedia.org/wiki/Fibonacci_heap) ... is best data structure for "priority queue" ...since supports "decraseKey" operation with O(1) time complexity.) 2. What is the input (format)? ("route" you would normally calculate on a "graph"...it looks like you process 1 "edge" (`String.split`) ...which can be "popped" from "pq") – xerx593 May 13 '18 at 11:36
  • @xerx593 I would _not_ recommend Fibonacci heap to someone just learning about Dijkstra's algorithm, it's way too much work for so little gain. – k_ssb May 13 '18 at 11:39
  • @Habil96 The geeksforgeeks pseudocode doesn't show you how to reconstruct the actual shortest path, it only shows you how to compute the path lengths. See https://stackoverflow.com/questions/28998597/how-to-save-shortest-path-in-dijkstra-algorithm (or Google "Dijkstra's path reconstruction") to see how to reconstruct the path. – k_ssb May 13 '18 at 11:41
  • My command is for examle "ROUTE A>D 3". And I have to find Route from A to D. However initally I want to just implement from just Source,A. I just can not find proper, reasonable implementation so that i can write it for my graph. The most understandable was the algorithm in geeksforgeeks and seems i am having traouble with this – Habil96 May 13 '18 at 11:55

0 Answers0