Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computational complexity of a longest path algorithm witn a recursive method

I wrote a code segment to determine the longest path in a graph. Following is the code. But I don't know how to get the computational complexity in it because of the recursive method in the middle. Since finding the longest path is an NP complete problem I assume it's something like O(n!) or O(2^n), but how can I actually determine it?

public static int longestPath(int A) {
    int k;
    int dist2=0;
    int max=0;

    visited[A] = true;

    for (k = 1; k <= V; ++k) {
        if(!visited[k]){
            dist2= length[A][k]+longestPath(k);
            if(dist2>max){
                max=dist2;
            }
        }
    }
    visited[A]=false;
    return(max);
}
like image 976
nirandi Avatar asked Dec 14 '10 10:12

nirandi


People also ask

What is the time complexity of recursive algorithm?

The number of levels in the recursion tree is log2(N). The cost at the last level where the size of the problem is 1 and the number of subproblems is N. The time complexity of the above recurrence relation is O(N logN).

How do you find the space complexity of a recursive algorithm?

To conclude, space complexity of recursive algorithm is proportinal to maximum depth of recursion tree generated. If each function call of recursive algorithm takes O(m) space and if the maximum depth of recursion tree is 'n' then space complexity of recursive algorithm would be O(nm).

How do you find the time complexity of a recursion tree?

T(F(I)) = T(F(I - 1)) + T(F(I - 1)) + O(1), so it looks like O(2^n).


1 Answers

Your recurrence relation is T(n, m) = mT(n, m-1) + O(n), where n denotes number of nodes and m denotes number of unvisited nodes (because you call longestPath m times, and there is a loop which executes the visited test n times). The base case is T(n, 0) = O(n) (just the visited test).

Solve this and I believe you get T(n, n) is O(n * n!).

EDIT

Working:

T(n, n) = nT(n, n-1) + O(n) 
        = n((n-1)T(n, n-2) + O(n)) + O(n) = ...
        = n(n-1)...1T(n, 0) + O(n)(1 + n + n(n-1) + ... + n(n-1)...2)
        = O(n)(1 + n + n(n-1) + ... + n!)
        = O(n)O(n!) (see http://oeis.org/A000522)
        = O(n*n!)
like image 156
lijie Avatar answered Sep 28 '22 11:09

lijie