#include <iostream>
using namespace std;
int calculate(int (*p)[100], int m, int n) {
int sum = 0;
if (m <= 2 || n <= 2) {//两行或两列以下的矩阵直接计算和
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
sum += p[i][j];
return sum;
}
for (int i = 1; i <= n; i++) {//第一行和最后一行的和
sum += p[1][i] + p[m][i];
}
for (int i = 2; i <= m - 1; i++) {第一列和最后一列的行(除去四个角的元素)
sum += p[i][1] + p[i][n];
}
return sum;
}
int main() {
int a[100][100] = { {0} }, sum, g, m, n;
cin >> g;
while (g > 0) {
cin >> m >> n;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &a[i][j]);
}
}
sum = calculate(a, m, n);
cout << sum << endl;
g--;
}
return 0;
}
poj 计算矩阵边缘元素之和
最新推荐文章于 2022-10-22 22:07:03 发布