Program to find the sum of elements that forms a Z shape on matrix in Python

Suppose we have one n x n matrix M, we have to find the sum of all elements that form a Z shape in the matrix.

A Z-shape consists of three parts: the first row (top horizontal line), the diagonal from top-right to bottom-left (middle diagonal), and the last row (bottom horizontal line).

Example Matrix

So, if the input is like ?

4 3 2
9 1 8
2 5 6

Then the output will be 23, as elements are [4+3+2+1+2+5+6] = 23.

Algorithm

To solve this, we will follow these steps ?

  • n := row count of matrix
  • if n <= 2, then
    • return sum of all elements in matrix
  • first_row := sum of first row
  • last_row := sum of last row
  • diagonal = sum of matrix[i, n-1-i] for all i from 1 to n-2
  • return first_row + last_row + diagonal

Implementation

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, matrix):
        n = len(matrix)
        if n <= 2:
            return sum(sum(row) for row in matrix)
        
        first_row = sum(matrix[0])
        last_row = sum(matrix[n-1])
        diagonal = sum(matrix[i][n-1-i] for i in range(1, n-1))
        
        return first_row + last_row + diagonal

# Test the solution
ob = Solution()
matrix = [
    [4, 3, 2], 
    [9, 1, 8], 
    [2, 5, 6]
]
print(ob.solve(matrix))

Output

23

How It Works

For the given 3x3 matrix:

  • First row: 4 + 3 + 2 = 9
  • Diagonal: matrix[1][1] = 1 (middle element)
  • Last row: 2 + 5 + 6 = 13
  • Total: 9 + 1 + 13 = 23

Edge Case

For matrices with n <= 2, all elements form the Z-shape, so we return the sum of all elements ?

ob = Solution()

# 2x2 matrix
matrix_2x2 = [
    [1, 2], 
    [3, 4]
]
print("2x2 matrix sum:", ob.solve(matrix_2x2))

# 1x1 matrix  
matrix_1x1 = [[5]]
print("1x1 matrix sum:", ob.solve(matrix_1x1))
2x2 matrix sum: 10
1x1 matrix sum: 5

Conclusion

The Z-shape sum algorithm efficiently calculates the sum by adding the first row, diagonal elements (excluding corners), and last row. For small matrices (n ? 2), all elements contribute to the Z-shape.

Updated on: 2026-03-25T10:41:47+05:30

498 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements