How to get the longest path in a DAG starting at a fixed node?

1.1k views Asked by At

I want to know how to get the longest path in a DAG starting from the node 0(the smallest node)

I searched wiki and got the following algorithm:

algorithm dag-longest-path is
input: 
     Directed acyclic graph G
output: 
     Length of the longest path

length_to = array with |V(G)| elements of type int with default value 0

for each vertex v in topOrder(G) do
    for each edge (v, w) in E(G) do
        if length_to[w] <= length_to[v] + weight(G,(v,w)) then
            length_to[w] = length_to[v] + weight(G, (v,w))

return max(length_to[v] for v in V(G))

but I don't know how to implement it, of course the following code I wrote doesn't work:(topo is the topological sorted nodes)

public static int longestPath(int[] topo){
    int[] dist = new int[topo.length];

    for(int i:topo){
        if(isArc(node,i)){
            if(dist[i]<dist[node]+1){
                dist[i] = dist[node] + 1;
            }
        }
    }
    return getMax(dist);
}

How should I do? Thanks!

Besides, could you give me an algorithm to calculate the number of different paths from 0 to n-1?

0

There are 0 answers