对角线遍历矩阵模板

主对角线方式遍历矩阵

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;
        }
    }
}
相关推荐
sprintzer3 小时前
1.6-1.15力扣数学刷题
算法·leetcode·职场和发展
jiang_bluetooth3 小时前
channel sounding基于探测序列的时延和相位差算法
算法·蓝牙测距·channel sound·gfsk·蓝牙6.0
地平线开发者3 小时前
征程 6 算法工具链 | PTQ 深度使用指南
算法·自动驾驶
Xの哲學4 小时前
Linux 软中断深度剖析: 从设计思想到实战调试
linux·网络·算法·架构·边缘计算
暴风游侠4 小时前
如何进行科学的分类
笔记·算法·分类
leaves falling4 小时前
冒泡排序(基础版+通用版)
数据结构·算法·排序算法
C雨后彩虹5 小时前
无向图染色
java·数据结构·算法·华为·面试
坚持就完事了5 小时前
扫描线算法
算法
鱼跃鹰飞5 小时前
Leetcode尊享面试100题:252. 会议室
算法·leetcode·面试
程序员-King.5 小时前
二分查找——算法总结与教学指南
数据结构·算法