Given a matrix of size n x n, find sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence cannot belong to same column.
Input : mat = 3 1 2 4 8 5 6 9 7 Output : 18 Zigzag sequence is: 3->8->7 Another such sequence is 2->4->7 Input : mat = 4 2 1 3 9 6 11 3 15 Output : 28
This problem has Optimal Substructure.
Maximum Zigzag sum starting from arr[i][j] to a bottom cell can be written as : zzs(i, j) = arr[i][j] + max(zzs(i+1, k)), where k = 0, 1, 2 and k != j zzs(i, j) = arr[i][j], if i = n-1 We have to find the largest among all as Result = zzs(0, j) where 0 <= j < n
Largest zigzag sum: 28
Considering the above implementation, for a matrix mat of size 3 x 3, to find zigzag sum(zzs) for an element mat(i,j), the following recursion tree is formed.
Recursion tree for cell (0, 0) zzs(0,0) / \ zzs(1,1) zzs(1,2) / \ / \ zzs(2,0) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 1) zzs(0,1) / \ zzs(1,0) zzs(1,2) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 2) zzs(0,2) / \ zzs(1,0) zzs(1,1) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,2)
We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem.
References: Asked in Directi
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print a given matrix in zigzag form
- Zigzag (or diagonal) traversal of Matrix
- Largest rectangular sub-matrix whose sum is 0
- Largest rectangular sub-matrix having sum divisible by k
- Given a matrix of 'O' and 'X', find the largest subsquare surrounded by 'X'
- Find the original matrix when largest element in a row and a column are given
- Largest area rectangular sub-matrix with equal number of 1's and 0's
- Find size of the largest '+' formed by all ones in a binary matrix
- Find the largest area rectangular sub-matrix whose sum is equal to k
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Find smallest and largest element from square matrix diagonals
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Check if matrix can be converted to another matrix by transposing square sub-matrices