0

I'm learning C language. And I want to find the longest acyclic path in a graph from A to B.

For example, I have a graph like this:

             0
             |
             1 
           /   \
          2 --- 3
          |    / \
          5---6---4

Now I want to write a function which can find the longest acyclic path from node A to node B.

input: longestPath(node A, node B) output: the longest length is x, node_a -> ... -> node_b

for example:

input: longestPath(0, 6) output: the longest length is 6, 0 -> 1 -> 2 -> 3 -> 4 -> 6 (the output answer may not unique, but one of the right answer)

But I have no idea how to implement a suitable algorithm to find it.

Should I use BFS or DFS to find all possible paths and compare them? (but it seems slow)

Could you please give me some advice? Thanks!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
user8400129
  • 193
  • 1
  • 7
  • 2
    Longest _acyclic_ path, I suppose: you can make a path of arbitrary length by looping (e.g., 0-1-2-3-1-2-3-1-2-3-1-2-3-4-6). – Arkku Aug 05 '19 at 11:59
  • Oh yes, the path should be acyclic, thanks! – user8400129 Aug 05 '19 at 12:04
  • 3
    The Longest Path Problem which is NP complete (it's a slightly different problem, but solving your problem would also solve that, so it's also hard), so asymptotically efficient approaches are unlikely – harold Aug 05 '19 at 12:04
  • Another observation is that the longest acyclic path is not necessarily unique, e.g., 0-1-3-2-5-6 is the same length as your example 0-1-2-3-4-6. I suppose that any path of the maximum length is a valid solution. – Arkku Aug 05 '19 at 12:19
  • You're right. Thanks! – user8400129 Aug 05 '19 at 12:29
  • 3
    The usual name for a path that doesn't use the same node twice is a _simple_ path. – hmakholm left over Monica Aug 05 '19 at 12:33
  • [Wikipedia article on longest path problem](https://en.wikipedia.org/wiki/Longest_path_problem) – pmg Aug 05 '19 at 13:23
  • You can try to transform your graph into a Directed Acyclic Graph, where the longest path problem can be solved in linear time. You can transform a regular graph into a DAG by finding all strongly connected components (SCCs): the graph of strongly connected components is always a DAG. Maybe such a transformation can help? – Xander Aug 12 '19 at 16:24

0 Answers0