0

I need to traverse a matrix on diagonals as in the following example. I tried to adapt the code from Traverse Matrix in Diagonal strips but I didnt succed.

Its a matrix of ints: int M[n][n];

example to traverse

order of diagonals to traverse:

  1. d(0)
  2. d(+1)
  3. d(-1)
  4. d(+2)
  5. d(-2)
  6. d(+3)
  7. d(-3) and so on

lets take this example:

00 01 02 03

10 11 12 13

20 21 22 23

30 31 32 33

so the output required will be:

slice 1: 00 11 22 33

slice 2: 01 12 23

slice 3: 10 21 32

slice 4: 02 13

slice 5: 20 31

slice 6 : 03

slice 7: 30

1 Answers1

0

You could try the following code, replacing printf by whatever you want.

#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");
    }
}
Loïc France
  • 305
  • 2
  • 10