【问题标题】:Multiple paths in Dijkstra's algorithmDijkstra 算法中的多条路径
【发布时间】:2015-06-25 22:00:54
【问题描述】:

我在我的一个项目中使用了 Dijksta 的方法。

我的问题是如何显示从 A 到 B 的所有最短路径(如果存在)。我的意思是,例如,如果有多个路径具有相同的最小长度。

这里是完整的代码:

class Vertex implements Comparable<Vertex> {
    public final String name;
    public Edge[] adjacencies;
    public double minDistance = Double.POSITIVE_INFINITY;
    public Vertex previous;

    public Vertex(String argName) {
        name = argName;
    }

    @Override
    public String toString() {
        return name;
    }

    @Override
    public int compareTo(Vertex other) {
        return Double.compare(minDistance, other.minDistance);
    }

}

class Edge {
    public final Vertex target;
    public final double weight;

    public Edge(Vertex argTarget, double argWeight) {
        target = argTarget;
        weight = argWeight;
    }

    public void computePaths(Vertex source) {
        source.minDistance = 0.;
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        while (!vertexQueue.isEmpty()) {
            Vertex u = vertexQueue.poll();

            // Visit each edge exiting u
            for (Edge e : u.adjacencies) {
                Vertex v = e.target;
                double weight = e.weight;
                double distanceThroughU = u.minDistance + weight;
                if (distanceThroughU < v.minDistance) {
                    vertexQueue.remove(v);

                    v.minDistance = distanceThroughU;
                    v.previous = u;
                    vertexQueue.add(v);
                }
            }
        }
    }

    public List<Vertex> getShortestPathTo(Vertex target) {
        List<Vertex> path = new ArrayList<Vertex>();
        for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
            path.add(vertex);

        Collections.reverse(path);
        return path;
    }
}

【问题讨论】:

  • Djkstra 的算法应该只给你一个可能的路径,即使可能存在其他同样短的路径。除非您想通过记录所有最短路径来修改算法。这就是你想要的吗?

标签: java dijkstra


【解决方案1】:

您需要一组先前的顶点而不是单个顶点。更新时发现等长路径,将顶点追加到前一个顶点列表中,在找到较短路径时清除并替换它。

然后处理要显示的内容取决于您正在使用它做什么。对于您现在拥有的不同路径,您需要递归遍历前辈以生成路径集。

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多