简体   繁体   中英

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.

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.

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