有向無環中的單源最短路徑問題

DAG-SHORTEST-PATHS(G,w,s)
1 topologically sort the verteces of G
2 INITIALIZE-SINGLE-SOURCE(G,s)
3 for each vertex u, taken in topologically sorted order
4   for each vertex v belong to G.Adj[u]
5     RELAX(u,v,w)

java代碼如下:

    /** * 有向無環圖中的單源最短路徑問題 * @param graphContent * @param startID * @throws Exception */
    @SuppressWarnings("rawtypes")
    public static void dag_shortest_paths(String graphContent, int startID) throws Exception{
        List<Vertex> vertexs = Topological_Sort.topo_sort(graphContent);

        initialize_single_source(vertexs, startID);
        LinkedList[] lists = Route.getLinkedList(graphContent);

        for (Vertex u : vertexs){
            for (int i = 1; i < lists[u.getID()].size(); i++){
                relax(Edge.getEdge(u.getID(), ((Vertex)lists[u.getID()].get(i)).getID()));
            }
        }
    }

    public static void print_path(String graphContent, int startID, int destID) throws Exception{
        dag_shortest_paths(graphContent, startID);

        LinkedList<Vertex> vertexs = new LinkedList<Vertex>();
        Vertex v = Vertex.getVertex(destID);
        vertexs.addFirst(v);
        while (!v.getParent().equal(startID)){
            vertexs.addFirst(v.getParent());
            v = v.getParent();
        }
        vertexs.addFirst(Vertex.getVertex(startID));
        for (Vertex vertex : vertexs){
            System.out.print(vertex + "(" + vertex.getD() + ") ");
        }
        System.out.println();
    }
点赞