i'm having a really tough time with this issue.
If I have a graphh, directed or undirected, unweighted and no cycles. How do I find the longest path? Many algorithms I have seen rely on the graph being weighted, and reverse the weights and use bellman ford. I ahve also seen dynamic programming solutions, but here people were simply looking for any path, I'm looking for one from s-t.
Ive been trying to break down the graph into subproblems, where I add one node a a time and give it a value of the parent that it is coming from plus one, but I just canoot get the logic right
can anyone provide an algorithm, exponential time would do, pseudopolynomial would be fantastic?
If the graph can be directed or undirected lets reduce the problem only to directed graphs. If it's undirected then you should make edges from v -> w and from w -> v. You can use modified DFS to measure the longest path starting from the node you pass to this function. Then run this function to every node and get the maximum value.
Pseudocode for DFS:
DFS(Node v):
if (v.visited?) return 0;
v.visited = true;
longestPath = 0;
foreach(Node n : v.neighbours):
longestPath = max(longestPath, DFS(n) + 1)
return longestPath
Pseudocode for the problem:
longestPath(Node[] verticies):
longestPath = 0
foreach(Node v : vertices):
foreach(Node w: vertices):
w.visited = false;
longestPath = max(longestPath, DFS(v))
return longestPath;
It works in O(n^2) but I think this solution is straight forward. Just to let you know, there is a solution which works O(n).