对角线遍历矩阵模板

主对角线方式遍历矩阵

cpp 复制代码
#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;
}

副对角线方式遍历矩阵

cpp 复制代码
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;
        }
    }
}
相关推荐
Swift社区16 分钟前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt55555555555542 分钟前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
让我们一起加油好吗1 小时前
【基础算法】DFS中的剪枝与优化
算法·深度优先·剪枝
Q741_1471 小时前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
Felven2 小时前
A. Be Positive
算法
小O的算法实验室2 小时前
2026年COR SCI2区,自适应K-means和强化学习RL算法+有效疫苗分配问题,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
青岛少儿编程-王老师3 小时前
CCF编程能力等级认证GESP—C++7级—20250927
数据结构·c++·算法
夏鹏今天学习了吗3 小时前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
天选之女wow4 小时前
【代码随想录算法训练营——Day34】动态规划——416.分割等和子集
算法·leetcode·动态规划
Boop_wu5 小时前
[数据结构] 哈希表
算法·哈希算法·散列表