主对角线方式遍历矩阵
#include<iostream>
#include<algorithm>
using namespace std;const int N = 510;int t, m[N][N];int diagonalTraverse(int matrix[][N], int n) {int rows = n;if (rows == 0) return 0;int cols = n;int sum = 0;// 遍历矩阵的所有对角线for (int d = 0; d < rows + cols - 1; ++d) {// 每条对角线的起始点int row = max(0, d - cols + 1);int col = max(0, cols - d - 1);int tmp = 0; //可修改// 打印当前对角线上的所有元素while (row < rows && col < cols) {tmp = min(tmp, matrix[row][col]); //可修改++row;++col;}sum += abs(tmp); // 可修改}return sum;
}int main()
{cin >> t;while (t--){int n; scanf("%d", &n);for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)scanf("%d", &m[i][j]);int sum = diagonalTraverse(m, n);printf("%d\n", sum);}return 0;
}
副对角线方式遍历矩阵
void diagonalTraverse(vector<vector<int>>& matrix) {int rows = matrix.size();if (rows == 0) return;int cols = matrix[0].size();// 遍历矩阵的所有对角线for (int d = 0; d < rows + cols - 1; ++d) {// 每条对角线的起始点int row = max(0, d - cols + 1);int col = min(d, cols - 1);// 打印当前对角线上的所有元素while (row < rows && col >= 0) {cout << matrix[row][col] << " ";++row;--col;}}
}