tags:

views:

809

answers:

3

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.

+6  A: 

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.

David Berger
+2  A: 

Please refer to the QuickGraph project as it provides .NET data structures implementing graphs, and also provides algorithms to operate on such data structures. I'm certain the algorithm you are looking for is implemented in the library.

Steve Guidi
+3  A: 

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.

wrang-wrang
A longest path can exist with cycles if they are not reachable. Moreover, Bellman-Ford can be made to return negative infinity if any negative-weight cycles are reachable. So this is still a reasonable question to ask even without explicitly assuming that the graph is acyclic. Perhaps this is why the first wikipedia article you link recommends Bellman-Ford.
David Berger
Sure, while you're preparing your topological order, DFS to detect whether the subgraph reachable from the source has a cycle.
wrang-wrang
The only reason to use bellman-ford for longest path is1) there are reachable cycles2) but all those cycles are 0 or negative weight (before weight inversion)
wrang-wrang