Dijkstra - 找到以前的矢量

时间:2014-01-09 15:26:10

标签: java algorithm path dijkstra

这是我的Dijkstra类的示例代码:

public class Dijkstra {

    public static int[] GetPath(IGraph graph,int start,int end){

    int[] dist=new int[graph.size()+1];
    Stack<Integer> Path =new Stack<Integer>();
    int[] previous=new int[graph.size()+1];
    boolean[] visited=new boolean[graph.size()+1];

    HashSet<Integer> Q=new HashSet<Integer>();

    int i,u = 0,min;

    for (i=0;i<graph.size();i++){
        dist[i]=10000;
        visited[i]=false;
        previous[i]=-1;     
    }
    dist[start]=0;  
    Q.add(start);

    while(!Q.isEmpty()){
        min=1000;   
        for(i=0;i<graph.size();i++){
            if(dist[i]<min&&visited[i]==false){
                min=dist[i];
                u=i;

            }
        }

        Q.remove(u);
        visited[u]=true;

        //Process all the outbound vertexes of the current vertex;
        int[] outb=graph.IterateOutbound(u);
        if(outb!=null){
            for (int v=0;v<outb.length-1;v++){
                int alt=dist[u]+graph.retrieveCost(u, outb[v]);
                if(alt<dist[outb[v]]&&!visited[outb[v]]){
                    dist[outb[v]]=alt;
                    previous[outb[v]]=u;
                    Q.add(outb[v]);

                }
            }
        }
    }
    return previous;
    }


}

我无法弄明白我如何使用“前一个”向量(在其中保存算法正在访问的每个顶点,直到成功,但不保存成本最低的那个)才能返回正确的路径 - 成本较低的那个。当我gooogled我已经看到我需要另一个函数(使用“前一个”向量)来计算路径。或者有人有另一个想法? “

附加信息:Graph是一个具有属性的类 - innies,outies,cost .. IterateOutbound是一个返回顶点出站顶点列表的函数 我从文件

中读取了信息

1 个答案:

答案 0 :(得分:1)

是的,您基本上需要更多代码行(可以放入函数中)来计算顶点的路径。

类似于:(伪代码)

Stack getPath(int[] previous, int start, int end)
   int current = end
   Stack path
   path.push(current)
   while (current != start)
      current = previous[current]
      path.push(current)
   return path

此算法的高级描述非常简单:

  • 从头开始
  • 反复查看前一个元素,直到我们开始,存储顶点,然后

为何选择Stack?因为我们正在从路径的末尾推送元素,所以我们推送的最后一个元素是start,如果使用Stack,它将是我们弹出的第一个元素。