I want to traverse a matrix in zig-zag fashion.
Say my matrix is
Code:
a11 a12 a13 a14
a21 a22 a23 a24
a31 a32 a33 a34
a41 a42 a43 a44
I want my output to be
Code:
a11 a12 a21 a31 a22 a13 a14 a23 a32 a41 a42 a33 a24 a34 a43 a44.
Here's how I tried to implement this :
For the upper triangle of the matrix,
(start at 0, 0)
1. move right once
2. move to the bottom left
3. move down once
4. move to the top right.
For the lower triangle of the matrix,
1. move right once
2. move to the top right
3. move down once
4. move to the bottom left.
The code for this works fine but it looks a bit messy and I think it can be optimized. Here's my code for an 8x8 matrix.
Code:
void zigzagOrder()
{
int i = 0;
int j = 0;
//for upper triangle of matrix
printf("%d, %d\t", i, j);
do
{
j++;
printf("\n");
printf("%d, %d\t", i, j);
while(j!=0)
{
i++;
j--;
printf("%d, %d\t", i, j);
}
i++;
if(i>7)
{
i--;
break;
}
printf("\n");
printf("%d, %d\t", i, j);
while(i!=0)
{
i--;
j++;
printf("%d, %d\t", i, j);
}
}
while(true);
//for lower triangle of matrix
do
{
j++;
printf("\n");
printf("%d, %d\t", i, j);
while(j!=7)
{
j++;
i--;
printf("%d, %d\t", i, j);
}
i++;
if(i>7)
{
i--;
break;
}
printf("\n");
printf("%d, %d\t", i, j);
while(i!=7)
{
i++;
j--;
printf("%d, %d\t", i, j);
}
}
while(true);
}
Please let me know if theres a better way to do this and how I can improve on my code.
Thanks