What is the worst case for this O (R * C) code?

I came across this question on InterviewBit:

int memo[101][101];
int findMinPath(vector<vector<int> > V, int r, int c) {
  int R = V.size();
  int C = V[0].size();
  if (r >= R || c >= C) return 100000000; // Infinity
  if (r == R - 1 && c == C - 1) return 0;
  if (memo[r][c] != -1) return memo[r][c];
  memo[r][c] =  V[r][c] + min(findMinPath(V, r + 1, c), findMinPath(V, r, c + 1));
  return memo[r][c];
}

Callsite : 
memset(memo, -1, sizeof(memo));
findMinPath(V, 0, 0);

Suppose that R = V.size()u C = V[0].size()and Vhave positive elements

Would the code create a binary tree-like function call that takes O (2 (m + n) ), since each function call calls two other function calls?

+4
source share
2 answers

This algorithm uses a method known as dynamic programming . The essence of this is to memorize intermediate results in the search table and search for a general solution in the form of a combination of partial solutions.

, findMinPath ( ) , memo . , memo , . R & times; C memo, .

, . memo , -1 ? , memset , . , , , R, C 101. , , .

+3

, (r, c)

:

memo [r] [c] = V [r] [c] + min (findMinPath (V, r + 1, c), findMinPath (V, r, c + 1));

[r] [c]

if (memo [r] [c]! = -1) [r] [c];

, 1 . , O (1) ( , [r] [c]! = -1 ).

O (R * C) , (r, c) , : O (R * C)

0

Source: https://habr.com/ru/post/1615147/


All Articles