Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest acyclic path in a directed unweighted graph

Tags:

What algorithm can be used to find the longest path in an unweighted directed acyclic graph?

like image 303
Hellnar Avatar asked Mar 26 '10 17:03

Hellnar


People also ask

How do you find the longest path in a directed acyclic graph?

Acyclic graphsA longest path between two given vertices s and t in a weighted graph G is the same thing as a shortest path in a graph −G derived from G by changing every weight to its negation. Therefore, if shortest paths can be found in −G, then longest paths can also be found in G.

Can DFS find longest path?

Efficient Approach: An efficient approach is to use Dynamic Programming and DFS together to find the longest path in the Graph. Let dp[i] be the length of the longest path starting from the node i. Initially all positions of dp will be 0. We can call the DFS function from every node and traverse for all its children.

What is an unweighted directed graph?

Unweighted graph is a type of graph with no edge weight. In an unweighted graph, the edges represent the connection between two nodes. If there is an edge between nodes u and v in an unweighted graph then u and v are adjacent to each other.


2 Answers

Dynamic programming. It is also referenced in Longest path problem, given that it is a DAG.

The following code from Wikipedia:

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)) 
like image 196
Larry Avatar answered Jan 02 '23 23:01

Larry


As long as the graph is acyclic, all you need to do is negate the edge weights and run any shortest-path algorithm.

EDIT: Obviously, you need a shortest-path algorithm that supports negative weights. Also, the algorithm from Wikipedia seems to have better time complexity, but I'll leave my answer here for reference.

like image 41
Can Berk Güder Avatar answered Jan 03 '23 00:01

Can Berk Güder