Dijkstra未对之前的节点阵列

时间:2016-11-26 18:21:14

标签: java dijkstra

使用Dijkstra进行路径查找,但每次运行算法时,我最终都没有对前一个节点数组进行更改。

public static int[] findRoute(Web m, int s)
{
    final int[] dist = new int[m.edges.length];         //shortest known dist from s
    final int[] pred = new int[m.edges.length];     //previous node in path
    final boolean[] visited = new boolean[m.edges.length];  //all start as false

    //sets each distance to max, until measured
    for(int i = 0; i < dist.length; i++)
    {  
        dist[i] = Integer.MAX_VALUE;
    }
    dist[s] = 0; //distance to self is 0 always

    for(int i = 0; i < dist.length; i++)
    {
        int next = minVertex (dist, visited);
        visited[next] = true;
        //shortest path to next is dist[next] and via pred[next]
        //counts roads that are connected
        int c = 0;

        for(int j = 0; j < m.edges[next].length; j++)
        {
            if(m.edges[next][j] > 0) c++;
        }
        //create array to hold connected road indexes
        int[] n = new int[c];
        //reset c
        c = 0;
        //loop to fill n with indexes of neighbors
        for(int j = 0; j < m.edges[next].length; j++)
            {if(m.edges[next][j]>0) n[c++] = j;}
        for(int j = 0; j < n.length; j++){
            final int v = n[j];
            final int d = dist[next] + m.edges[next][v];
            if (dist[v] > d) {
                dist[v] = d;
                pred[v] = next;
            }
        }
    }
    return pred; //ignore pred[s] == 0
}

Web类只是一个2D数组,如果存在连接,则保存节点之间的距离。经过一些测试后,看起来pred并没有在第一轮之后更新。如何更改它以正确更新pred数组?这是我第一次尝试使用该算法,我已经通过一堆伪代码读取了它,但我还没有弄清楚我哪里出错了。目前,当我尝试打印路径时,我只是获取目标,然后是无限的节点0。

minVertex

private static int minVertex(int[] dist, boolean[] v)
{
    int x = Integer.MAX_VALUE;
    int y = -1; //graph not connected or no unvisited
    for(int i = 0; i < dist.length; i++)
    {
        if(!v[i] && dist[i] < x) 
        {
            y = i;
            x = dist[i];
        }
    }
    System.out.println(y);
    return y;
}

边缘和交叉点

  • 交点1:X = 0,Y = -1
  • 交叉点2:X = 0,Y = 0
  • 交点3:X = 1,Y = 0
  • 交叉点4:X = 1,Y = 3
  • 交点5:X = 0,Y = 3
  • 交叉点6:X = 2,Y = 3

边缘都是500长,边是

  • I2-I1
  • I1-I2
  • I2-I3
  • I3-I4
  • 6-14 12-15
  • I5-I2
  • I2-I5
  • I6 6-14

1 个答案:

答案 0 :(得分:0)

The code you put in your answer is a correct implementation of O(V^2) array Dijkstra. Based on your description of the issue, I believe the problem is that in your minVertex() code (which you ddin't provide), you need to check if the vertex is visited and only return the minimum distance among non-visited vertices.

Let me know if this fixes the problem. If not, could you please edit your question to provide the rest of your code?