What is the point of adding and removing the element from Priority Queue in the given dijkstra code?

风格不统一 提交于 2019-12-02 18:03:33

问题


I was studying Dijkstra algorithm code given at this link -> https://java2blog.com/dijkstra-java/

Can someone explain the following 2 parts of the code?

1) Why are we adding and removing the element from Priority queue when calculate distance is less?

if( newDistance < v.getDistance() ) {
    priorityQueue.remove(v);
    v.setDistance(newDistance);
    v.setPredecessor(actualVertex);
    priorityQueue.add(v);
}

2) What are we doing in compareTo method and why?

@Override
public int compareTo(Vertex otherVertex) {
    return Double.compare(this.distance, otherVertex.getDistance());
}

回答1:


To begin with, this code is bad, since priorityQueue.remove(v) requires O(n) time, which defeats the whole purpose of using PriorityQueue https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/PriorityQueue.html:

... linear time for the remove(Object) ...

2) Dijkstra's algorithm in one phrase: select a non-visited vertex with a smallest distance. To extract the vertex with a smallest distance, you maintain a priority queue, where you compare vertices by distance (this is what your compareTo does). So the vertex which is extracted will be the vertex with the smallest distance.

1) Data structures have some assumptions. If these assumptions are violated, data structures may work incorrectly. In case of PriorityQueue the assumption is "for any elements in the queue the result of comparison doesn't change". And, since you compare using distance, if you change the distance, then the result of comparison may also change, leaving your PriorityQueue in potentially invalid state. Therefore, you first remove the element, and only after that change the distance.




回答2:


1) PriorityQueue only evaluates priority when entries are inserted. Just changing the priority on v will not cause this evaluation, so it will have no effect.

2) The basic contract for compareTo is that it returns 0 iff both instances or considered equal. 1 if this is considered "bigger" -1 if this is considered "smaller". Double.compare(..) creates this semantic for a Double value.



来源:https://stackoverflow.com/questions/57844537/what-is-the-point-of-adding-and-removing-the-element-from-priority-queue-in-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!