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.
For Example :
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.
Output Format :
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.
Note :
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
2
3
0 1 0
1 0 1
1 0 1
2
1 1
-1 1
5
3
In the first test case, the most optimal path will be (0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (2, 2) -> (2, 1) -> (2, 0) -> (1, 0) -> (0, 0). Hence the total gold collected is 5.
In the second test case, the one and only path will be (0, 0) -> (0, 1) -> (1, 1) -> (0, 1) -> (0, 0). Hence the total gold collected is 3.
2
1
0
2
1 -1
-1 1
0
0
Recursively check for all the possible paths and return the max answer.
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:
greedyJewellerHelper(x1, y1, x2):
O( 4 ^ N ), where N is the length of the square matrix.
As we are going through all the paths.
Hence the time complexity is O( 4 ^ N ).
O( 1 )
No extra space is used.
Hence the space complexity is O(1).