简体   繁体   English

Java源代码和目标代码中的Dijkstra算法

[英]Dijkstra's algorithm in Java source and target

I'm trying to use Dijkstra's algorithm to find the shortest path between two nodes in the graph. 我正在尝试使用Dijkstra的算法来找到图中两个节点之间的最短路径。

what should I do to the following code to stop calculating when the shortest path between the source and the target is found? 找到源与目标之间的最短路径后,如何对以下代码停止计算?

public void calculate(Vertex source){
    // Algo:
    // 1. Take the unvisited node with minimum weight.
    // 2. Visit all its neighbours.
    // 3. Update the distances for all the neighbours (In the Priority Queue).
    // Repeat the process till all the connected nodes are visited.

    source.minDistance = 0;
    PriorityQueue<Vertex> queue = new PriorityQueue<Vertex>();
    queue.add(source);

    while(!queue.isEmpty()){

        Vertex u = queue.poll();

        for(Edge neighbour:u.neighbours){
            Double newDist = u.minDistance+neighbour.weight;

            if(neighbour.target.minDistance>newDist){
                // Remove the node from the queue to update the distance value.
                queue.remove(neighbour.target);
                neighbour.target.minDistance = newDist;

                // Take the path visited till now and add the new node.s
                neighbour.target.path = new LinkedList<Vertex>(u.path);
                neighbour.target.path.add(u);

                //Reenter the node with new distance.
                queue.add(neighbour.target);                    
            }
        }
    }
}

what should I do to the following code to stop calculating when the shortest path between the source and the target is found 当找到源和目标之间的最短路径时,我应该对以下代码做什么以停止计算

You can't "break" in the middle because you can't tell if there isn't a shorter path than the one you've already found until the algorithm finishes. 您不能在中间“中断”,因为在算法完成之前,您无法确定是否没有比您已经找到的路径更短的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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