[코테 풀이] Matrix Diagonal Sum

시내·2024년 6월 7일

Q_1572) Matrix Diagonal Sum

출처 : https://leetcode.com/problems/matrix-diagonal-sum/?envType=study-plan-v2&envId=programming-skills

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

class Solution {
    public int diagonalSum(int[][] mat) {
        int primary = 0;
        int secondary = 0;
        if (mat.length == 1) return mat[0][0];
        else {
            if (mat.length % 2 != 0) { //repetitive
                for (int i = 0; i < mat.length; i++) {
                    primary += mat[i][i];
                }
                for (int j = 0; j < mat.length; j++) {
                    if (j != mat.length - 1 - j) {
                        secondary += mat[j][mat.length - j - 1];
                    }
                }
            } else {
                for (int i = 0; i < mat.length; i++) {
                    primary += mat[i][i];
                }
                for (int j = 0; j < mat.length; j++) {
                    secondary += mat[j][mat.length - j - 1];
                }
            }
        }
        return primary + secondary;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글