How to traverse a 2D array in zigzag order

user3437460 picture user3437460 · Apr 4, 2014 · Viewed 8.1k times · Source

We have an int 2D array as follow:

int matrix[4][4] =
{{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
{13,14,15,16}};

By convention if we wants to print out the array by order we can:

    for (int x=0; x<4; x++)
    {
        for (int y=0; y<4; y++) 
        {                                        
            cout << matrix[x][y] << "  ";
        }   
        cout << endl;               
    }

Output:

 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16

My question is: How can we traverse the 2D array in zigzag order. For example, print out the array values as such:

 1  2  3  4  
 8  7  6  5
 9 10 11 12
16 15 14 13

Answer

iavr picture iavr · Apr 4, 2014

How about

bool r=false;
for (int x=0; x<4; x++)
{
    for (int y=0; y<4; y++)
    {
        cout << matrix[x][r ? 3-y : y] << "  ";
    }
    cout << endl;
    r = !r;
}