Dijkstra算法多边缘找到最小值

时间:2016-11-29 11:16:02

标签: java algorithm graph dijkstra

我一直试图找到一种方法来获得图中顶点之间的最小距离和路径。我找到了一个解决方案,我适应了我的必需品,它主要起作用。我正在谈论的实施: http://www.vogella.com/tutorials/JavaAlgorithmsDijkstra/article.html#shortestpath_problem

只有一个问题是我要问的问题。正如你所看到的那样,只有一条边链接着两个顶点,如果是这样,我得到了我想要的结果。 但是,在测试类中,如果我只是添加另一个边连接,让我们说Vertex 1和Vertex 2的重量低于另一个,如下所示:

addLane("Edge_0", 0, 1, 85);
addLane("Edge_1", 0, 2, 217);
addLane("Edge_12", 0, 2, 210); //as you can see, added this one 
addLane("Edge_2", 0, 4, 173);
addLane("Edge_3", 2, 6, 186);
addLane("Edge_4", 2, 7, 103);
addLane("Edge_5", 3, 7, 183);
addLane("Edge_6", 5, 8, 250);
addLane("Edge_7", 8, 9, 84);
addLane("Edge_8", 7, 9, 167);
addLane("Edge_9", 4, 9, 502);
addLane("Edge_10", 9, 10, 40);
addLane("Edge_11", 1, 10, 600);

在这种情况下(假设我试图找到从顶点0到10的路径/距离)我仍然得到正确的路径(Vertex_0 - > Vertex_2 - > Vertex_7 - > Vertex_9 - > Vertex_10)但是如果我只是这样做:

dijkstra.getShortestDistance(nodes.get(10)); //to get the distance from the source to the destination which in this case is the Vertex_10

当它应该是520时,它会给我一个错误的距离(527),因为我从vertex_0到vertex_2的另一个边添加了一个较低的权重,因此它应该计算该权重,而不是前一个更大的权重。

我不知道我是否清楚自己,但如果你有任何想法,我很感激。

注意:我没有粘贴其余部分,所以这不会变得很大但是检查链接,它就在那里

1 个答案:

答案 0 :(得分:1)

因为getDistance方法。此方法假定节点,目标对仅由一条边连接。

private int getDistance(Vertex node, Vertex target) {
    for (Edge edge : edges) {
        if (edge.getSource().equals(node) && edge.getDestination().equals(target)) {
            return edge.getWeight();
        }
    }
    throw new RuntimeException("Should not happen");
}

在这种情况下,它会找到" Edge_1"在达到" Edge_12"之前成本为217成本210。

对此的快速解决方法是首先找到连接两个节点的所有边的最小值:

private int getDistance(Vertex node, Vertex target) {
    Integer weight = null;
    for (Edge edge : edges) {
        if (edge.getSource().equals(node) && edge.getDestination().equals(target)) {
            if (weight == null || edge.getWeight() < weight) {
                weight = edge.getWeight();
            }
        }
    }
    if (weight == null) { 
        throw new RuntimeException("Should not happen");
    }
    return weight;
}