You are given a matrix ‘MAT’ of dimensions ‘N x N’. Let’s define a sequence to be ‘zigzag’ if it starts from the top and ends at the bottom such that no two consecutive elements of the sequence belong to the same column.
Your task is to find the sum of the zigzag sequence with the largest sum.
Input Format :
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains a single positive integer, ‘N’, as described in the problem statement.
The next ‘N’ lines of each test case contains ‘N’ space-separated number, ‘MAT[i][j]’, representing the value at index (i,j) of the matrix.
Output Format :
For each test case, print the “sum of the zigzag sequence with the largest sum”, as described in the problem statement.
Output for each test case will be printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 100
1 <= MAT[i][j] <= 1000
Where 'MAT[i][j]' denotes the value of matrix at 'jth' column of 'ith' row.
Time Limit: 1sec
1
2
1 3
2 4
5
There are only two possible zigzag sequences:
(i) 1 -> 4 with sum eqaul to 5.
(ii) 3 -> 2 with sum equal to 5.
Hence both are optimal zigzag sequences with a sum equal to 5.
1
3
1 2 3
3 4 5
4 5 6
13
The optimal zigzag sequence is 3 -> 4 -> 6 with a sum eqaul to 13.
Try to find all possible zigzag sequences using recursion.
O(N^N), where N is the number of rows and columns in the matrix.
We are using the recursion for forming all possible zigzag sequences. As in each function call, we have ‘N’ options available. Hence, the time complexity will be O(N^N).
O(1).
As we are only using the constant extra space.