Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest Path between two vertices

Tags:

c#

algorithm

I have a directed graph with weighted edges (weights are all positive).

Now, I'm looking for an efficient algorithm or code (specifically, C#) to find the longest path between two given vertices.

like image 989
Hamid Avatar asked Dec 18 '22 06:12

Hamid


2 Answers

This is exactly equivalent to a shortest-path algorithm with all negative weights. To do that, you need to verify that there are no negative-weight cycles (which in your original case is probably equivalent to verifying no positive-weight cycles). Best bet is to take the additive inverse of the weights and run Bellman-Ford, then take the additive inverse of the result.

like image 89
David Berger Avatar answered Dec 19 '22 21:12

David Berger


David Berger's answer is correct, unless you mean a simple path, where each vertex can occur at most once, in which case Bellman-Ford will not give the longest path. Since you say the weights are positive, it's not possible for a longest path to exist when the graph has a cycle (reachable from the source), unless you mean simple path. The longest simple path problem is NP-complete. See Wikipedia.

So, let's assume you mean a directed acyclic graph (DAG). In linear time, you can compute the longest path to each vertex v from the start vertex s, given that you know the longest path from s->*u for each u where u->v directly. This is easy - you can do a depth first search on your directed graph and compute the longest path for the vertices in reverse order of visiting them. You can also detect back edges whole you DFS using a 3-color marking (opened but not finished vertices are gray). See Wikipedia again for more information. Longest/shortest path finding on a DAG is sometimes called the Viterbi algorithm (even though it was given assuming a specific type of DAG).

I'd attempt the linear time dynamic programming solution first. If you do have cycles, then Bellman-Ford won't solve your problem anyway.

like image 36
Jonathan Graehl Avatar answered Dec 19 '22 19:12

Jonathan Graehl