


While moving towards the lower right corner, he can only go in two directions, i.e., right and down and while returning, he can only move in the directions left and up.
If there is no valid path, he cannot collect any gold.
N = 3, mat = {{1, 1, 1}, {0, -1, 0,}, {1, 1, 1}}
In this example, the jeweler will first follow the path: (0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (2, 2) and then return from the path (2, 2) -> (2, 1) -> (2, 0) -> (1, 0) -> (0, 0). Hence the total gold collected will be 6.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’ denoting the size of the square matrix.
The next ‘N’ lines contain ‘N’ integers, each containing 0, 1, -1, denoting the matrix’s values.
For each test case, print a single integer denoting the total gold collected by the jeweler.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 100
Time limit: 1 sec
Approach: In this approach, instead of going from the top left to the bottom right and then returning, we will go from the top left to the bottom right two times simultaneously.
The steps are as follows:
In this approach, instead of going from the top left to the bottom right and then returning, we will go from the top left to the bottom right two times simultaneously.
The steps are as follows:
greedyJewellerHelper(x1, y1, x2):
In this approach, the computation of the ‘i’ step ‘dp’ result only uses the i - 1 step ‘dp’ result and uses no dp results, which are before the i - 1 step. So we can memorize only the last step (i - 1) ‘dp’ result at each ‘i’ loop. Thus we can reduce the space complexation to O (N^2).
The steps are as follows: