对角线遍历矩阵模板

主对角线方式遍历矩阵

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;
        }
    }
}
相关推荐
m0_603888711 天前
Scaling Trends for Multi-Hop Contextual Reasoning in Mid-Scale Language Models
人工智能·算法·ai·语言模型·论文速览
Xの哲學1 天前
Linux io_uring 深度剖析: 重新定义高性能I/O的架构革命
linux·服务器·网络·算法·边缘计算
comli_cn1 天前
残差链接(Residual Connection)
人工智能·算法
Aaron15881 天前
基于VU13P在人工智能高速接口传输上的应用浅析
人工智能·算法·fpga开发·硬件架构·信息与通信·信号处理·基带工程
予枫的编程笔记1 天前
【论文解读】DLF:以语言为核心的多模态情感分析新范式 (AAAI 2025)
人工智能·python·算法·机器学习
im_AMBER1 天前
Leetcode 99 删除排序链表中的重复元素 | 合并两个链表
数据结构·笔记·学习·算法·leetcode·链表
王老师青少年编程1 天前
信奥赛C++提高组csp-s之欧拉回路
c++·算法·csp·欧拉回路·信奥赛·csp-s·提高组
墨有6661 天前
数学分析栈的出栈顺序:从算法判断到数学本质(卡特兰数初探)
c++·算法·数学建模
zhutoutoutousan1 天前
氛围数学学习:用游戏化思维征服抽象数学
学习·算法·游戏
victory04311 天前
pytorch 矩阵乘法和实际存储形状的差异
人工智能·pytorch·矩阵