Dijkstras的优化

时间:2015-12-16 12:03:05

标签: dijkstra

我想帮助优化此代码。在我的部分 初始化所有的ArrayLists,感觉不够我必须设置 它们是路径ArrayList大小的默认值,因为我只是 感兴趣的是从源节点到目标节点的路径。你有没有 伙计们对如何解决这个问题有任何想法?

干杯!

//Shortest path algorithm
public void shortestPath(String source, String end){    

    /*
     * Init the vertices, init the distances
     * Set the distance from the start node to itself to 0
     */
    copy = g.getMap();  

    initArrays(copy);

    holdCost.add(agent.get(source), 0);
    pq.insert(new Vertex(source, 0));

    while(!pq.isEmpty()){
        Vertex v = pq.getRoot();
        pq.delete(pq.getRoot());

        visited.set(agent.get(v), true);    
        for(Edge e : copy.get(v)){
            if(!visited.get(agent.get(e))){
                if(holdCost.get(agent.get(e)) > (holdCost.get(agent.get(v))    
                 + e.getWeight())){
                    holdCost.set(agent.get(e), (holdCost.get(agent.get(v)) 
                                                        + e.getWeight()));
                    pq.insert(new Vertex(path.get(agent.get(e)),
                                   holdCost.get(agent.get(e))));
                    cost.add(holdCost.get(agent.get(e)));
                }if(visited.get(agent.get(end))){
                    break;
                }
            }               
        }               
    }
}

//Initiliaze of distance, nodes etc
public void initArrays(HashMap<String, ArrayList<Edge>> h){
    for(String s : h.keySet()){
        path.add(s);
        holdCost.add(path.indexOf(s), Integer.MAX_VALUE);
        visited.add(path.indexOf(s), false);
        agent.put(s, path.indexOf(s)); //easy to get the same index as  vertices, distances etc
    }

}

0 个答案:

没有答案