我需要在对角线上遍历矩阵,如下例所示。 我尝试改编 Traverse Matrix in Diagonal strips 中的代码但我没有成功。
它是一个整数矩阵:int M[n][n];
遍历对角线的顺序:
- d(0)
- d(+1)
- d(-1)
- d(+2)
- d(-2)
- d(+3)
- 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/