Dijkstra算法Java - 找到最短路径

时间:2013-11-27 06:10:55

标签: java algorithm dijkstra

我需要在我的情况下实现Dijsktra算法: 从A到B到达目的地的时间是5。 从A到C到达目的地的时间是3.(从A到C(1),从C到B(2)=>到它的3。

我在下面尝试:

    public static void main(String[] args)
    {
        // mark all the vertices 
        Vertex A = new Vertex("A");
        Vertex B = new Vertex("B");
        Vertex C = new Vertex("C");


        // set the edges and weight
      A.adjacencies = new Edge[]{ new Edge(B, 5) };
      C.adjacencies = new Edge[]{ new Edge(A, 1) };
      B.adjacencies = new Edge[]{ new Edge(C, 2) };


        computePaths(A); // run Dijkstra
        System.out.println("Distance to " + B + ": " + B.minDistance);
        List<Vertex> path = getShortestPathTo(B);
        System.out.println("Path: " + path);
    }

http://pastebin.com/jGynb3t8 我错了什么?我需要找到最短的B路径。

1 个答案:

答案 0 :(得分:1)

你的边缘类犯了错误。在computePaths

的这一部分
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
    Vertex v = e.target;

您认为边缘始终指向沿最短路径。但对于eA之间的边C,它保留了e.target == A,因为您创建了它为

C.adjacencies = new Edge[]{ new Edge(A, 1) };

您应该将computePaths中的行更改为

Vertex v = (e.source == u ? e.target : e.source);
相关问题