Example
Input : 5
10 13 10 12 15
12 39 30 23 11
11 25 50 53 15
19 27 29 37 27
19 13 30 13 19
Output : 155
My answer:
import java.util.Scanner;
class MatrixMaxSum {
public static void main(String[] args) {
MatrixMaxSum t = new MatrixMaxSum();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int[][] a = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
a[i][j] = kb.nextInt();
}
}
System.out.println(t.solution(n, a));
}
int solution(int n, int[][] a) {
int max = 0;
for(int i = 0; i < n; i++) {
int tmp = 0;
for(int j = 0; j < n; j++) {
tmp += a[i][j];
}
if(tmp > max) max = tmp;
}
for(int i = 0; i < n; i++) {
int tmp = 0;
for(int j = 0; j < n; j++) {
tmp += a[j][i];
}
if(tmp > max) max = tmp;
}
int tmp2 = 0;
for(int i = 0; i < n; i++) {
tmp2 += a[i][i];
}
if(tmp2 > max) max = tmp2;
int tmp3 = 0;
for(int i = 0; i < n; i++) {
tmp3 += a[i][n-1-i];
}
if(tmp3 > max) max = tmp3;
return max;
}
}
- Input Reading:
- It uses a Scanner to read the input.
- Reads an integer n, representing the size of the square matrix.
- Reads the elements of the matrix (a) row by row.
- Matrix Sum Calculation:
- The solution method calculates the sum of each row and updates the max variable if a larger sum is found.
- It then calculates the sum of each column and updates max accordingly.
- The sums of the main diagonal and the secondary diagonal are calculated and compared with max.
- Output:
- The final maximum sum is printed to the console.
메모장에 완벽하게 설계했고, 재밌게 코딩했는데 결과가 다르게 나와서 당황했다..
'tmp2 += a[i][i];' 를 'tmp2 = a[i][i];' 로 했던 것...
이런 오류는 발견하기 힘드니 꼼꼼하게 코딩해야겠다..
'Language > Algorithm' 카테고리의 다른 글
Matrix Analyzer (2) | 2023.12.21 |
---|---|
Array Analyzer (1) | 2023.12.19 |
Element Ranking Code (0) | 2023.12.16 |
Count Consecutive 1s Total (0) | 2023.12.14 |
Number Reversal Prime Check (0) | 2023.12.13 |