在对角线条中遍历矩阵 [英] Traverse Matrix in Diagonal strips

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

问题描述

我认为这个问题有一个简单的解决方案,几个 for 循环和一些花哨的计数器,但显然它相当复杂.

I thought this problem had a trivial solution, couple of for loops and some fancy counters, but apparently it is rather more complicated.

所以我的问题是,你将如何(用 C 语言)编写一个函数遍历对角线条中的方阵.

So my question is, how would you write (in C) a function traversal of a square matrix in diagonal strips.

示例:

1  2  3
4  5  6
7  8  9

必须按以下顺序遍历:

[1],[2,4],[3,5,7],[6,8],[9]

上面的每个条带都用方括号括起来.要求之一是能够区分条带.这意味着您知道何时开始新的条带.这是因为我必须为条带中的每个项目调用另一个函数,然后在新条带开始之前调用.因此,没有代码重复的解决方案是理想的.

Each strip above is enclosed by square brackets. One of the requirements is being able to distinguish between strips. Meaning that you know when you're starting a new strip. This because there is another function that I must call for each item in a strip and then before the beginning of a new strip. Thus a solution without code duplication is ideal.

推荐答案

这里有一些你可以使用的东西.只需将 printfs 替换为您真正想做的事情.

Here's something you can use. Just replace the printfs with what you actually want to do.

#include <stdio.h>

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

输出:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆