-
47일 (1572. Matrix Diagonal Sum) matrix 쉬움지식/알고리즘 2023. 11. 6. 20:07
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행을 순회하는 반복문 하나와, 포인터 2개만 있으면 될 것같다.
- 코드
class Solution { public int diagonalSum(int[][] mat) { int length = mat.length; // 1 int ptr1 = 0; int ptr2 = mat[0].length-1; int sum = 0; if(ptr2 % 2 == 0) sum -= mat[ptr2/2][ptr2/2]; // 2 for(int i = 0; i < length; i++) { // 3 if(ptr2 >= 0 && ptr1 <= length-1) { sum += mat[i][ptr1++]; sum += mat[i][ptr2--]; } else break; } return sum; } }
1. 각 행에 포인터 2개에 위치하는 값을 sum에 더할 예정이다.
2. n*n배열이 주어질 때 배열이 n이 홀수라면 교체하는 값이 있으므로 중복값을 빼준다.(ex1의 5)
3. 배열의 범위 내에 위치하는 ptr1 ptr2가 가르키는 원소를 교차시켜가면서 sum에 더해준다.
'지식 > 알고리즘' 카테고리의 다른 글
49일 (1582. Special Positions in a Binary Matrix) matrix (0) 2023.11.08 48일 (2643. Row With Maximum Ones) matrix (0) 2023.11.07 46일 (1260. Shift 2D Grid) matrix 참신함 (0) 2023.11.05 45일 (419. Battleships in a Board) matrix (0) 2023.11.04 44일 (807. Max Increase to Keep City Skyline) matrix 어려움 (0) 2023.11.03