简体   繁体   中英

Dijkstra's algorithm using the priority queue

So I am trying to implement Dijkstra's algorithm using the priority queue data structure in java. Since comparable operator in java cannot compare two variables, so i need to "modify its Comparator . How do I modify it ?

 while(!Q.isEmpty()){
         int index = Q.peek().edge;
         long d = Q.peek().dis;
         Q.remove();

         if(d!=D[index]) continue; // HERE I AM CHECKING IF IT ALREADY PROCEEDED OR NOT

         for(int i=0;i<maps[index].size();i++){
               int e = maps[index].get(i).edge;
                d =  maps[index].get(i).dis;
                if(D[e]>D[index]+d){
                    D[e]= D[index]+d;
                    Q.add(new Node(e,D[e])); // NEED TO MODIFY
                }
         }
     }



Then i came across this code:

 while (!q.isEmpty()) {
      long cur = q.remove();
      int curu = (int) cur;
      if (cur >>> 32 != prio[curu])
        continue;
      for (Edge e : edges[curu]) {
        int v = e.t;
        int nprio = prio[curu] + e.cost;
        if (prio[v] > nprio) {
          prio[v] = nprio;
          pred[v] = curu;
          q.add(((long) nprio << 32) + v);
        }

How q.add(((long) nprio << 32) + v); and cur >>> 32 != prio[curu] statements works. Please HElp.

Java's Priorityqueue sorts according to the natural ordering if no comparator is given.

You either need to:

  1. implement compareTo in your Node class
  2. create a Comparator that compares your nodes according to priority (priority = distance from start for Dijkstra)

The second code you showed uses the upper 32 bits of a long to store the priority, thereby making the natural order reflect the distance from start.

Basically, the code is 100% the same as yours, with the difference being the data structure. You use a class, the second code uses a long to embed two integers (node id and distance/priority).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM