


1 -> The cell contains an apple that Alice can pick up and pass through it.
-1 -> The cell contains a bush and Alice can not visit this cell.
0 -> The cell is empty and Alice can pass through it.
1. After picking an apple the cell will become empty.
2. While going towards the bottom right corner, Alice can either move Right or Down at each step.
3. While going towards the top left corner, Alice can either move Left or Up at each step.
4. If there is no path from (0,0) to (‘N’-1, ‘N’-1) then Alice will not pick any apple.
If the given matrix is :
[1, 1, -1, 1]
[1, 0, 1, 1]
[1, 1, 0, 1]
[0, -1, -1, 1]
One of the possible ways to collect maximum apples is :
Path for going towards bottom right corner:
(0,0) -> (0,1) -> (1,1) -> (1,2) -> (1,3) -> (2,3) -> (3,3)
Apples collected are equal to 6.
Path for going towards top left corner:
(3,3) -> (2,3) ->(2,2) -> (2,1) -> (2,0) -> (1,0) -> (0,0)
Apples collected are equal to 3.
So Alice can collect a maximum of 9 apples.
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains a space-separated integer ‘N’ representing the number of rows and columns.
The next ‘N’ lines of each test case contain ‘N’ single space-separated integers denoting the values of ‘MATRIX’.
For each test case, print a single line containing a single integer representing the maximum number of apples Alice can collect.
The output of every test case will be printed in a separate line.
You don’t have to print anything, it has already been taken care of. Just implement the given function.
1 <= T <=10
1 <= N <= 50
-1 <= MATRIX[i] <= 1
Where ‘T’ denotes the number of test cases, ‘N’ denotes the number of rows and columns of ‘MATRIX’.
Time limit: 1 sec.
Complete Algorithm:
Our last approach was very simple and easy, but its time complexity was of exponential order. We can improve our solution by taking care of the overlapping subproblems. Thus, we will eliminate the need for solving the same subproblems again and again by storing them in a lookup table. This approach is known as Memoization.
We will initialize a 3-D array say ‘MEMO[N][N][N]’ with -1, where ‘N’ is the number of rows and columns. Where ‘MEMO[R1][C1][C2]’ equals -1 means the current state is not explored. Otherwise, ‘MEMO[R1][C1][C2]’ represents the max number of apples that can be collected by 2 people going from ‘R1’, ‘C1’ and ‘R2’, ‘C2’ to ‘N’-1, ‘N’-1.
As our earlier approach recursion with memoization surely avoided some subproblems but we can still improve time complexity using a bottom-up approach and we will also reduce the space complexity to O(N^2).