• • ## zigzag matrix traversing

Given an square matrix of size NxN , traverse the matrix in zig zag order. for example see the below matrix  as input of your program. Write a program in c such that the output would give 1 2 6 3 5 4 4 5 6 7 5 6 8 7 6 7 8 7 6 9 6 5 8 7 9. These type of questions generally asked in interview and it is very hard to think the solution, if some one is not familiar of the right approach to solve the problem.

## solution:

```#include<stdio.h>

#define r 5
#define c 5

/* print zigzag elements */
void zigagElements(int mat[][c], int row, int col);

int main() {

int m[] = { { 1, 2, 3, 4, 5 },
{ 6, 5, 5, 6, 7 },
{ 4, 6, 8, 8, 9 },
{ 7, 7, 7, 6, 8 },
{ 6, 6, 5, 7, 9 } };
printf("The spiral elements are:\n");

/*call printSpiralElements */
zigagElements(m, r, c);
return 0;
}

void zigagElements(int mat[][c], int row, int col) {
int i = 0, j = 0;

while (i < row) {

printf("%d ", mat[i][j]);
if (i == row - 1) {
i = j + 1;
j = col - 1;
} else if (j == 0) {
j = i + 1;
i = 0;
}

else {
j--;
i++;
}

}

printf("\n");
}
```

output:

```
The spiral elements are:
1 2 6 3 5 4 4 5 6 7 5 6 8 7 6 7 8 7 6 9 6 5 8 7 9
```

Reference:

http://www.sumeetkataria.com/2012/12/print-two-dimensional-matrix-in-zigzag-form/