A naive approach can go through all possible vertex permutations.
For each permutation {v1, ..., vN} you can check if you can get from v1 to v2 , then from v2 to v3 , etc. If possible, add the appropriate edge length to the current path length. If not, continue to the next permutation.
The longest of these paths is your answer.
Or you could do almost the same thing with recursion.
path = 0 bestPath = 0 used = new bool[N] // initialize with falses for(u = 0; u < N; u++) Path(u); // build paths starting from u print bestPath
Where
Path(u) used[u] = true foreach v in neighborhood(u) if(!used[v]) path += distance(u, v) bestPath = max(bestPath, path) Path(v) path -= distance(u, v) used[u] = false
The complexity of time is terrible O(N * N^N) .
Alexd source share