- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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

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 ob = Solution() matrix = [ [4, 3, 2], [9, 1, 8], [2, 5, 6] ] print(ob.solve(matrix))

matrix = [[4, 3, 2], [9, 1, 8], [2, 5, 6]]

23

- Related Questions & Answers
- Program to find number of distinct quadruple that forms target sum in python
- Program to find diagonal sum of a matrix in Python
- Program to check some elements in matrix forms a cycle or not in python
- Python Program to Print Matrix in Z form
- C Program to print the sum of boundary elements of a matrix
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- Program to find sum of all elements of a tree in Python
- Program to find the perimeter of an island shape in Python
- Python Program to find the transpose of a matrix
- Find sum of elements in list in Python program
- How to find the sum of anti-diagonal elements in a matrix in R?
- How to find the sum of all elements of a given matrix using Numpy?
- Find the transpose of a matrix in Python Program
- Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python

Advertisements