【问题标题】:Dijkstra's algorithm in Java source and targetJava源和目标中的Dijkstra算法
【发布时间】:2017-02-10 21:30:11
【问题描述】:

我正在尝试使用 Dijkstra 算法来找到图中两个节点之间的最短路径。

当找到源和目标之间的最短路径时,我应该如何处理以下代码以停止计算?

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);                    
            }
        }
    }
}

【问题讨论】:

    标签: java graph dijkstra


    【解决方案1】:

    我应该对以下代码做些什么来停止计算当 找到源和目标之间的最短路径

    您不能在中间“中断”,因为在算法完成之前,您无法判断是否没有比您已经找到的路径更短的路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多