Sum of Elements in the ZigZag Sequence in a given Matrix in Java using Recursion
ADVERTISEMENTS
Sum of elements in the zigzag sequence in a given matrix in java using the recursion. In this program, you will learn how to find the sum of elements in the zigzag sequence in a given matrix in java using recursion.
Source Code
// Sum of Elements in the ZigZag Sequence in a given Matrix in Java using Recursion
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 3;
int[][] arru = {
{23, 23, 27, 21},
{35, 36, 37, 38},
{49, 40, 41, 41},
{53, 54, 55, 56}
};
// arru - this variable contains the
// input matrix to find the largest sum
System.out.println("The largest zigzag sum of the matrix is: " + largestZigZag(arru, n));
}
public static int zigZagSum(int[][] arru, int i, int j, int n) {
// If we have reached bottom
if (i == n - 1)
return arru[i][j];
// This will find the largest
// sum in the sequence
int zzs = 0;
for (int k = 0; k < n; k++)
if (k != j)
zzs = Math.max(zzs, zigZagSum(arru, i + 1, k, n));
return zzs + arru[i][j];
}
public static int largestZigZag(int[][] arru, int n) {
// This will consider all cells of
// top row as starting point
int res = 0;
for (int j = 0; j < n; j++)
res = Math.max(res, zigZagSum(arru, 0, j, n));
return res;
}
}
Output
The largest zigzag sum of the matrix is: 112