在对角线条中遍历矩形矩阵

在对角线条中遍历矩形矩阵

本文介绍了在对角线条中遍历矩形矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在这里做同样的事情,但要处理任何矩阵,不只是一个正方形.此外,遍历的方向需要相反.我试图编辑我在那里找到的代码,但无法弄清楚.

I need the same thing done here, but to work with any matrix, not just a square one. Also, the direction of traversal needs to be opposite. I tried to edit the code I found there, but couldn't figure it out.

谢谢.

推荐答案

我记得我是这么写的.我认为对于矩形矩阵,您需要进行一些细微的更改和一行难以理解的废话:

I remember writing that. I think for a rectangular matrix you'd need a few minor changes and one more line of incomprehensible nonsense:

#include <stdio.h>

int main()
{
    int x[3][4] = { 1,  2,  3,  4,
                    5,  6,  7,  8,
                    9, 10, 11, 12};
    int m = 3;
    int n = 4;
    for (int slice = 0; slice < m + n - 1; ++slice) {
        printf("Slice %d: ", slice);
        int z1 = slice < n ? 0 : slice - n + 1;
        int z2 = slice < m ? 0 : slice - m + 1;
        for (int j = slice - z2; j >= z1; --j) {
                printf("%d ", x[j][slice - j]);
        }
        printf("
");
    }
    return 0;
}

输出:

Slice 0: 1
Slice 1: 5 2
Slice 2: 9 6 3
Slice 3: 10 7 4
Slice 4: 11 8
Slice 5: 12

简单解释一下它是如何工作的,每个切片都是一条对角线,从第一列开始,向右对角线向上并在第一行结束(最初是左下角,但现在根据海报的评论进行了交换).

To briefly explain how it works, each slice is a diagonal starting from the first column, going diagonally up-right and ending on the first row (originally down-left, but now swapped as a result of a comment from the poster).

z2 表示在打印第一个数字之前必须跳过多少个项目.对于前 m 个切片,该值为零,然后对于每个剩余的切片增加 1.z1 是最后应该跳过多少个项目,同样从前 m 个切片的零开始,剩余的切片增加 1.

z2 says how many items must be skipped before the first number should be printed. This is zero for the first m slices and then increases by one for each remaining slice. z1 is how many items should be skipped at the end, again starting at zero for the first m slices, and increasing by one for the remaining slices.

这篇关于在对角线条中遍历矩形矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:06