Find the absolute difference of the matrix diagonals.
Example:
Input: mat={{1,2,3},{4,5,6},{7,8,9}}
Output: 2
Approach
Java
public class MatrixDiagonalDiff {public static void main(String[] args) {// given input matrix as square matrixint matrix[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 8, 9 } };int sum = diagonalDiff(matrix);System.out.println(sum);}public static int diagonalDiff(int[][] matrix) {int sumL = 0;int sumR = 0;int n = matrix.length;for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {if (i == j) {sumL += matrix[i][j];}if (i == n - 1 - j) {sumR += matrix[i][j];}}}return Math.abs(sumL - sumR);}}
C++
#include <bits/stdc++.h>using namespace std;int main(){vector<vector<int>> mat={{1 ,2, 3},{4, 5, 6},{9, 8, 9}};int sum1=0,sum2=0;int n=mat.size();for(int i=0;i<n;i++){for(int j=0;j<n;j++){if(i==j)sum1=sum1+mat[i][j];if(i==n-1-j)sum2=sum2+mat[i][j];}}int res=abs(sum1-sum2);cout<<res<<"\n";return 0;}
No comments:
Post a Comment