4
votes

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.

4
Have you made an attempt? If so, could you edit to include your idea? - statenjason
@David, Yeah, sounds like a project for an Algorithms course. - Steve

4 Answers

7
votes

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.

3
votes

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.

2
votes

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.

0
votes

Just in case it helps anyone, as I was looking for this for a while but couldn't find it, I used QuickGraph to solve a problem where I had to find the longest path that also complies with a certain rule. It is not very elegant as I did it a bit on brute force once I get the first result, but here it is.

https://github.com/ndsrf/random/blob/master/LongestSkiPath/LongestSkiPath/SkiingResolver.cs#L129-L161

To get the longest path you use an algorithm to find the shortest with lenghts = -1. And then to find subsequent longest paths I start removing edges from that longest path to see if I manage to get a "better" (based on the conditions of the problem) longest path.