Sum of Elements in the ZigZag Sequence in a given Matrix in C using Recursion
ADVERTISEMENTS
Sum of elements in the zigzag sequence in a given matrix in C using recursion. In this article, you will learn how to find the sum of elements in the zigzag sequence in a given matrix in c using recursion.
Source Code
// Sum of Elements in the ZigZag Sequence in a given Matrix in C using Recursion
#include <stdio.h>
#define MAX 100
#define max(a, b)(((a) > (b)) ? (a) : (b))
int zigZagSum(int arru[][MAX], int i, int j, int n) {
// If we have reached bottom
if (i == n - 1)
return arru[i][j];
// It will find the largest sum in the sequence
int zzs = 0;
for (int k = 0; k < n; k++)
if (k != j)
zzs = max(zzs, zigZagSum(arru, i + 1, k, n));
return zzs + arru[i][j];
}
int largestZigZag(int arru[][MAX], int n) {
// It will consider all cells of top row as starting point
int res = 0;
for (int j = 0; j < n; j++)
res = max(res, zigZagSum(arru, 0, j, n));
return res;
}
int main() {
int n = 3;
int arru[][MAX] = {
{43, 23, 67, 41},
{15, 16, 17, 18},
{19, 10, 11, 21},
{23, 24, 25, 26}
};
// arru - denotes the input matrix to find the largest sum
printf("The largest zigzag sum of the matrix is: %d\n", largestZigZag(arru, n));
return 0;
}
Output
The largest zigzag sum of the matrix is: 102