Find the sum of the diagonal elements of the matrix.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Approach
Java
public class MatrixDiagonalSum {public static void main(String[] args) {// given input matrix as square// matrixint matrix[][] = { { 1, 1, 1, 1 }, { 1, 1, 1, 1 },{ 1, 1, 1, 1 }, { 1, 1, 1, 1 } };int sum = diagonalSum(matrix);System.out.println(sum);}public static int diagonalSum(int[][] matrix) {int sum = 0;int n = matrix.length;for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {if (i == j) {sum += matrix[i][j];if (j != n - 1 - j) {sum += matrix[i][n - 1 - j];}}}}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the sum of//matrix of the square matrixint diagonalSum(vector<vector<int>> &matrix){int sum = 0;int n = matrix.size();for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){if (i == j) {sum += matrix[i][j];if (j != n - 1 - j) {sum += matrix[i][n - 1 - j];}}}}return sum;}int main(){// given input matrix as square// matrixvector<vector<int>> matrix = { { 1, 1, 1, 1 }, { 1, 1, 1, 1 },{ 1, 1, 1, 1 }, { 1, 1, 1, 1 } };int sum = diagonalSum(matrix);cout<<sum<<"\n";return 0;}
No comments:
Post a Comment