Longest Path in a Directed Acyclic Graph | Set 2
Given a Weighted Directed Acyclic Graph (DAG) and a source vertex in it, find the longest distances from source vertex to all other vertices in the given graph.
We have already discussed how we can find Longest Path in Directed Acyclic Graph(DAG) in Set 1. In this post, we will discuss another interesting solution to find longest path of DAG that uses algorithm for finding Shortest Path in a DAG.
The idea is to negate the weights of the path and find the shortest path in the graph. A 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.
Below is the step by step process of finding longest paths –
We change weight of every edge of given graph to its negation and initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph which represents a linear ordering of the graph. When we consider a vertex u in topological order, it is guaranteed that we have considered every incoming edge to it. i.e. We have already found shortest path to that vertex and we can use that info to update shorter path of all its adjacent vertices. Once we have topological order, we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent vertex using shortest distance of current vertex from source vertex and its edge weight. i.e.
for every adjacent vertex v of every vertex u in topological order if (dist[v] > dist[u] + weight(u, v)) dist[v] = dist[u] + weight(u, v)
Once we have found all shortest paths from the source vertex, longest paths will be just negation of shortest paths.
Below is the implementation of the above approach:
Following are longest distances from source vertex 1 INT_MIN 0 2 9 8 10
Time Complexity: Time complexity of topological sorting is O(V + E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. As total adjacent vertices in a graph is O(E), the inner loop runs O(V + E) times. Therefore, overall time complexity of this algorithm is O(V + E).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.