What is the time-complexity of the the algorithm (in pseudo-code) below? I have had a hard time analyzing it. It is an implementation of the problem specified at another thread: Algorithm to find max cost path of length N in matrix, from [0,0] to last row. But because I’m new here I don’t have points enough to comment in the thread (I think)?. This is my first post, so excuse me if i did something wrong.
The algorithm uses memoization with the cache[][][][]. During the initialization cache[][][][] is filled with -1.
The method is called with maxPath(0,0,m,DOWN). Where m is the amount of steps to take, n<=m<=n^2 and the directions are defined as DOWN=0, LEFT=1, RIGHT=2.
function maxPath(i, j, fuel, direction)
if i = n OR j = n OR j < 0 OR fuel = 0 then
return 0;
end if
if cache[i][j][f-1][d] != -1 then
return cache[i][j][f - 1][d];
end if
ret := 0
acc+ = matrix[i][j]
ret:=max(ret,maxPath(i+1, j, fuel-1, DOWN))
if f > n - i then . If there is enough steps to move horizontally
if d = RIGHT or d = DOWN then
ret:=max(ret,maxPath(i, j+1, fuel-1, RIGHT))
end if
if d = LEFT or d = DOWN then
ret:=max(ret,maxPath(i, j-1, fuel-1, LEFT))
end if
end if
return cache[i,j,fuel-1,direction] = ret + matrix[i][j]
end function
Okey I have solved it and was thinking that I should share my results.
If we let G=(V,E) be a graph where V={maxPath(i, j, p, d) : for all possible i, j, p and d } and E= {uv : u = f(i, j, p, d) and v = f(i’, j’, p’, d’) }. We have that G is a graph of states which is clearly DAG (directed acyclic graph). Then, we can compute maxPath with memoization.
We have
Then we have n * n * m * 3 differents functions of maxPath to be called which is n^4*3 in worst case. So, we have O(n^4) different functions. Each call of function runs in O(1) time. Because the graph has a suboptimal structure, each subproblem is problem of the original one. So with memoization we dont have to compute the same ‘function’ two times, thus we get O(n^4).