gpt4 book ai didi

c - 遍历矩阵的相邻对角线

转载 作者:行者123 更新时间:2023-11-30 19:29:05 24 4
gpt4 key购买 nike

我需要在对角线上遍历矩阵,如下例所示。我尝试改编 Traverse Matrix in Diagonal strips 中的代码但我没有成功。

它是一个整数矩阵:int M[n][n];

example to traverse

遍历对角线的顺序:

  1. d(0)
  2. d(+1)
  3. d(-1)
  4. d(+2)
  5. d(-2)
  6. d(+3)
  7. d(-3)等等

让我们举个例子:

00 01 02 03

10 11 12 13

20 21 22 23

30 31 32 33

因此所需的输出将是:

切片 1: 00 11 22 33

切片 2:01 12 23

切片 3:10 21 32

切片 4:02 13

切片 5:20 31

切片 6:03

切片 7: 30

最佳答案

您可以尝试以下代码,将 printf 替换为您想要的任何内容。

#define N 4

int M[N][N];
//populate the array
for(int i=0; i<N; ++i)
{
printf("slice %d:", 2*i+1);
for(int j=0; j<N-i; ++j)
printf(" %d", M[j][j+i]);
printf("\n");
if(i > 0)
{
printf("slice %d:", 2*i+2);
for(int j=0; j<N-i; ++j)
printf(" %d", M[j+i][j]);
printf("\n");
}
}

关于c - 遍历矩阵的相邻对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com