Given: An unweighted, directed Graph (G=(E,V)), which can contain any number of cycles.
Goal: For all vertices I want the longest simple path to some target vertex X in V
Algorithm Idea:
For each v in V
v.distanceToTarget = DepthFirstSearch(v)
Next
DepthFirstSearch(v as Vertex)
if v = target then
'Distance towards target is 0 for target itself
return 0
elseif v.isVisitedInCurrentDFSPath then
'Cycle found -> I wont find the target when I go around in cycles -> abort
return -infinity
else
'Return the maximum Distance of all Successors + 1
return max(v.Successors.ForEach(Function(v) DepthFirstSearch(v) )) + 1
end if
Is this correct for all cases? (Assuming, that the target can be reached from every vertex)
The number of edges in my graphs is very small. Assume |E| <= 3*|V| holds. How would I compute the average time complexity?
Thanks!