对角线遍历矩阵模板

主对角线方式遍历矩阵

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;
        }
    }
}
相关推荐
程序员东岸几秒前
《数据结构——排序(中)》选择与交换的艺术:从直接选择到堆排序的性能跃迁
数据结构·笔记·算法·leetcode·排序算法
程序员-King.3 分钟前
day104—对向双指针—接雨水(LeetCode-42)
算法·贪心算法
神仙别闹27 分钟前
基于C++实现(控制台)应用递推法完成经典型算法的应用
开发语言·c++·算法
Ayanami_Reii28 分钟前
进阶数据结构应用-一个简单的整数问题2(线段树解法)
数据结构·算法·线段树·延迟标记
劈星斩月1 小时前
3Blue1Brown《线性代数的本质》矩阵与线性变换
线性代数·矩阵·线性变换
listhi5201 小时前
基于改进SET的时频分析MATLAB实现
开发语言·算法·matlab
Keep_Trying_Go2 小时前
基于Zero-Shot的目标计数算法详解(Open-world Text-specified Object Counting)
人工智能·pytorch·python·算法·多模态·目标统计
xl.liu2 小时前
零售行业仓库商品数据标记
算法·零售
confiself2 小时前
通义灵码分析ms-swift框架中CHORD算法实现
开发语言·算法·swift
做怪小疯子2 小时前
LeetCode 热题 100——二叉树——二叉树的层序遍历&将有序数组转换为二叉搜索树
算法·leetcode·职场和发展