[LeetCode] 1572. Matrix Diagonal Sum - Java
알고리즘/LeetCode

[LeetCode] 1572. Matrix Diagonal Sum - Java

반응형

https://leetcode.com/problems/matrix-diagonal-sum/description/

 

Matrix Diagonal Sum - LeetCode

Can you solve this real interview question? Matrix Diagonal Sum - 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

leetcode.com


문제

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.

 

Example 1:

Input: mat = [[1,2,3],
              [4,5,6],
              [7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.

Example 2:

Input: mat = [[1,1,1,1],
              [1,1,1,1],
              [1,1,1,1],
              [1,1,1,1]]
Output: 8

Example 3:

Input: mat = [[5]]
Output: 5

 

Constraints:

  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100

풀이

풀이 과정

길이가 n인 정사각형 모양의 2차원 배열 mat가 주어질 때 왼쪽 위부터 오른쪽 아래로 향하는 대각선상에 위치한 요소들과 오른쪽 위부터 왼쪽 아래로 향하는 대각선상에 위치한 요소들의 총합을 구하는 문제이다.
단 두 대각선상에서 중복되는 요소는 한 번만 더하도록 한다.

우선 총 합계를 저장할 변수와 배열의 길이를 저장할 변수를 선언하고 초기화한다.

// 대각선 요소의 총 합계
int sum = 0;

// 배열의 길이
int length = mat.length;

 

우선 배열의 길이가 1인 경우 요소는 하나만 존재하고 대각선으로 나타낼 경우 중복되어 한 번만 합계에 추가해야하기 때문에 해당 요소를 바로 return한다.

// 배열의 길이가 1인 경우 요소를 바로 return
if(length == 1) return mat[0][0];

 

배열의 길이가 1보다 큰 경우에는 배열의 길이만큼 반복하며 각 행의 요소를 탐색한다.

현재 탐색중인 행이 n번째 행이라고 할 때 왼쪽 위에서 오른쪽 아래로 향하는 대각선에 해당하는 요소는 mat[n][n] 으로 나타낼 수 있다. 따라서 합계에 mat[n][n]을 더해준다.

다음으로 오른쪽 위에서 왼쪽 아래로 향하는 대각선에 해당하는 요소는 mat[n][배열의 길이 - n - 1]로 나타낼 수 있다.
해당 요소 역시 합계에 더해주는데 두 대각선에서 중복되는 요소인 경우에는 더하지 않는다.
배열의 길이가 홀수이면서 현재 탐색중인 행의 인덱스가 배열의 절반인 경우 중복되는 요소가 된다.

// 배열의 길이만큼 반복
for(int i = 0; i < length; i++){
    // primary diagonal
    sum += mat[i][i];

    // secondary diagonal
    // 배열의 길이가 홀수 이면서 길이의 절반에 해당하는 인덱스인 경우
    // 중복된 요소가 선택되므로 탐색제외
    if(length % 2 == 1 && i == length / 2) continue;
    // 이외의 경우 합계에 더함
    sum += mat[i][length - i - 1];
}

 

최종적으로 구해진 합계를 return한다.

return sum;

최종 코드

class Solution {
    public int diagonalSum(int[][] mat) {
        // 대각선 요소의 총 합계
        int sum = 0;

        // 배열의 길이
        int length = mat.length;

        // 배열의 길이가 1인 경우 요소를 바로 return
        if(length == 1) return mat[0][0];

        // 배열의 길이만큼 반복
        for(int i = 0; i < length; i++){
            // primary diagonal
            sum += mat[i][i];

            // secondary diagonal
            // 배열의 길이가 홀수 이면서 길이의 절반에 해당하는 인덱스인 경우
            // 중복된 요소가 선택되므로 탐색제외
            if(length % 2 == 1 && i == length / 2) continue;
            // 이외의 경우 합계에 더함
            sum += mat[i][length - i - 1];
        }

        return sum;
    }
}