calgorithmtime-complexitybig-ohamiltonian-cycle

Time Complexity in code?


I have fun1 calls foo1() which takes O(n^6 + m^4). What do you think the time complexity of fun1? My guess is it would be O(2n^6 + m^4) !!

int fun1(int n, int G[MAX][MAX])
{
  int x, ans;
  if(n < 2)
     return 1;
  for(x = 0; x < n; x++){
    G[n][x] = G[x][n] = 1;
  }
  ans = foo1(n+1, G);
  return ans;
}

Also fun2 calls foo2() which takes O(n^3 + m^2). What do you think the time complexity of fun2? My guess is O(n^3 + m^2 + 2n^2) !!

 int fun2(int n, int G[MAX][MAX])
 {
   int x, y, i, j;
   int ans = y = 0;
   int arr[MAX][MAX] = {};
   for(i = 0; i < n; i++) {
     for(j = 0; j < n; j++)
       arr[i][j] = G[i][j];
   }

   if(n <= 2)
     return 0;
   for(x = 0; x < n; x++){
     if(arr[y][x] && arr[x][y]){
       arr[y][x] = arr[x][y] = 0;
       arr[n+1][x] = arr[x][n+1] = 1;
       arr[y][n] = arr[n][y] = 1;
       if(foo2(n+2, arr))
         ans = 1;
       arr[n][y] = arr[y][n] = 0;
       arr[n+1][x] = arr[x][n+1] = 0;
       arr[y][x] = arr[x][y] = 1;
       if(ans == 1)
         break;
     }    
   }
   return ans;
  }

Am I right?


Solution

  • For fun1(), I do not agree with you. In the body of the function there is a for loop that takes O(n) and then foo1(n+1, G), which takes O((n+1)6 + m4). Putting them together, we get:

    O(n) + O((n+1)6 + m4) = O(n) + O(n6 + m4) = O(n6 + m4)


    I am afraid I do not agree with your second guess either, since what you have there is two for loops, which made you guessed what you guessed.

    However, please notice that the second calls foo2(n+2, arr) in its body. As a result, foo2() will be called n times!

    Putting everything together, we have:

    first for loop + second for loop = O(n) + O(n(n + 2)3 + nm2) = O(n) + O(n4 + nm2) = O(n4 + nm2)