【问题标题】:Dijkstra algorithm optimization regarding priority queueu关于优先级队列的 Dijkstra 算法优化
【发布时间】:2013-09-13 15:17:12
【问题描述】:

我在模拟中使用下面的代码。因为我一遍又一遍地调用 dijkstra 方法,所以性能对我来说非常重要。 ,我使用 PriorityQueue 来保持图形的节点相对于它们到源的距离按升序排列。 PriorityQueue 使我能够以 O(log n) 复杂度访问距离最小的节点。然而, 为了在重新计算节点距离后保持节点有序,我需要先删除节点,然后再添加它。我想可能有更好的方法。我感谢任何反馈。提前感谢所有社区。​​p>

    public HashMap<INode, Double> getSingleSourceShortestDistance(INode sourceNode) {
    HashMap<INode, Double> distance = new HashMap<>();
    PriorityQueue<INode> pq;

   // The nodes are stored in a priority queue in which all nodes are sorted      

   according to their estimated distances.



    INode u = null;
    INode v = null;
    double alt;


    Set<INode> nodeset = nodes.keySet();
    Iterator<INode> iter = nodeset.iterator();
    //Mark all nodes with infinity
    while (iter.hasNext()) {
        INode node =  iter.next();
        distance.put(node, Double.POSITIVE_INFINITY);
        previous.put(node, null);
    }
    iter = null;

    // Mark the distance[source] as 0
    distance.put(sourceNode, 0d);


    pq = new PriorityQueue<>(this.network.getNodeCount(), new NodeComparator(distance));

    pq.addAll(nodeset);

    // Loop while q is empty
    while (!pq.isEmpty()) {
        // Fetch the node with the smallest estimated distance. 
        u = pq.peek();
        /**
         * break the loop if the distance is greater than the max net size.
         * That shows that the nodes in the queue can not be reached from
         * the source node.
         */
        if ((Double.isInfinite(distance.get(u).doubleValue()))) {

            break;
        }
        // Remove the node with the smallest estimated distance.
        pq.remove(u);

        // Iterate over all nodes (v) which are neighbors of node u
        iter = nodes.get(u).keySet().iterator();
        while (iter.hasNext()) {
            v = (INode) iter.next();
            alt = distance.get(u) + nodes.get(u).get(v).getDistance();
            if (alt < distance.get(v)) {
                distance.put(v, alt);
                //To reorder the queue node v is first removed and then inserted.
                pq.remove(v);
                pq.add(v);



            }
        }
    }



    return distance;



}

    protected static class NodeComparator<INode> implements Comparator<INode> {

    private Map<INode, Number> distances;

    protected NodeComparator(Map<INode, Number> distances) {
        this.distances = distances;
    }

    @Override
    public int compare(INode node1, INode node2) {
        return ((Double) distances.get(node1)).compareTo((Double) distances.get(node2));
    }
}

【问题讨论】:

    标签: algorithm graph-theory priority-queue dijkstra


    【解决方案1】:

    您可以使用实现了 increase_key 和 reduction_key 的堆,这样您就可以更新节点距离而无需重新删除和添加它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多