กำหนด square matrix หาจำนวนแถวและคอลัมน์ที่ผลรวมเท่ากับ ผลรวม diagonal หลัก (principal) หรือ diagonal รอง (secondary)
ตัวอย่าง:
4 1 7 10 3 5 2 2 11Principal: 4+3+11=18, Secondary: 7+3+2=12 Row sums: 12, 18, 15 → match 2 rows Col sums: 16, 6, 23 → match 0 Output:
2
วิธีแก้ปัญหา
- คำนวณ principal diagonal sum (i==j) และ secondary (i+j==n-1)
- คำนวณผลรวมแต่ละแถวและแต่ละคอลัมน์
- นับจำนวนที่เท่ากับ diagonal ไหนก็ได้
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int diagonal_sum(int matrix[3][3]) {
int principal = 0, secondary = 0;
for(int i=0;i<3;i++) {
principal += matrix[i][i];
secondary += matrix[i][2-i];
}
int count = 0;
for(int i=0;i<3;i++) {
int row=0, col=0;
for(int j=0;j<3;j++) {
row += matrix[i][j];
col += matrix[j][i];
}
if(row==principal || row==secondary) count++;
if(col==principal || col==secondary) count++;
}
return count;
}
int main() {
int matrix[3][3] = {{4,1,7},{10,3,5},{2,2,11}};
cout << diagonal_sum(matrix);
}
Input
{{4,1,7},{10,3,5},{2,2,11}}
Output
2