在对角线条导线矩阵 [英] Traverse Matrix in Diagonal strips

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

问题描述

我觉得这个问题有一个简单的解决方案,夫妇的循环和一些奇特的柜台,但显然这是相当复杂。

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

将不得不遍历顺序如下:

Would have to be traversed in the following order:

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

以上各条放在方括号内。 一的要求是能够带之间进行区分。这意味着当你开始一个新的带,你知道的。这是因为存在着我必须调用的每个项目中的条带和另一功能然后一个新的条带的开始之前。因此,没有code复制的解决方案是理想的。

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("\n");
    }
    return 0;
}

输出:

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

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

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