Python Online Compiler
Example: Sum of Elements in the ZigZag Sequence in a given Matrix in Python using Recursion
C
C++
C#
Java
Python
PHP
main.py
STDIN
Run
# Sum of Elements in the ZigZag Sequence in a given Matrix in Python using Recursion # This function will calculate # the sum of the list elements def zigZagSum(arru, i, j, n): pass # If we have reached bottom if i == n - 1: return arru[i][j] # This will find the largest sum in the sequence zzs = 0 for k in range (n): if k != j: zzs = max(zzs, zigZagSum(arru, i + 1, k, n)) return zzs + arru[i][j] # This function will calculate # the largest sum of elements def largestZigZag(arru, n): pass res = 0 # This will consider all cells of top row as starting point for j in range (n): res = max(res, zigZagSum(arru, 0, j, n)) return res # This is the driven calculation # It's the size matrix dimensions n = 4 arru = [ [43, 43, 47, 41], [35, 36, 37, 38], [29, 20, 21, 21], [13, 14, 15, 16] ] print ("The largest zigzag sum of the matrix is:", largestZigZag(arru, n))
Output
Clear
ADVERTISEMENTS