How to find a path in graph with maximum edges?

How can I find the longest simple path in a directed, not necessarily acyclic graph?

  • There's no start node or goal node- I want the longest contiguous path. It can begin anywhere, can end anywhere as long as the total path is the longest possible. I guess the recurrence for Dynamic Programming would be something like: ds(u,v)=max(ds−1(u,v)+1) d_{s}(u, v) = max(d_{s-1}(u, v) + 1) But I'm having trouble thinking how to code this. Any pointers would be awesome.

  • Answer:

    Let f(x) be the longest path ending at node x. Your recurrence is f(x) = 1 + max( f(y) ), where y are all parents of x, or 0 if x has no parent. You can compute this efficiently by traversing the DAG in toposort order, i.e. compute f(x) before f(y) for any (x,y) such that there is an edge from x to y. Edit: The original version of this question was about acyclic graphs. As the question title has changed, this answer is less relevant.

Steven Hao at Quora Visit the source

Was this solution helpful to you?

Other answers

Consider this reduction from a general undirected graph G(u) to the directed graph G(d). Now, for each edge, u-v in the undirected graph G(u), you can add two directed edges u ->v and v -> u . Now , the longest path in the directed graph G(d) would also be the longest path in the undirected graph G(u) and vice -versa due to the above construction.  So , if supposedly , we can find the longest path in the current  directed graph in polynomial time , then we can solve the problem of solving longest path in undirected graph in polynomial time too ( which is impossible of course ,as finding longest path in an undirected graph is NP-complete)

Piyush Gaurav

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.