如何以Z字形顺序遍历2D数组

时间:2014-04-04 15:52:46

标签: c++ arrays zigzag

我们有一个int 2D数组如下:

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

按照惯例,如果我们想按顺序打印出数组,我们可以:

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

输出

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

我的问题是:我们如何以Z字形顺序遍历2D数组。例如,打印出数组值:

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

4 个答案:

答案 0 :(得分:3)

怎么样

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;
}

答案 1 :(得分:1)

这是一个解决方案(在您编辑原始问题之前,您要求在不使用if()或条件的情况下解决原始问题):

#include <iostream>
using namespace std;
int main()
{
    int matrix[4][4] =
        {{1,2,3,4},
        {5,6,7,8},
        {9,10,11,12},
        {13,14,15,16}};

    bool backwards = false;        
    int incre = 1;
    for (int x=0; x < 4; x++)
    {
        int index = 3 * backwards;
        for (int y=0; y<4; y++, index += incre) 
            cout << matrix[x][index] << "  ";
        incre = -incre;
        backwards = !backwards;
        cout << endl;               
    }
}

诀窍是你希望列数增加一行,减少下一行等等。这就是增量变量的原因。

&#34;向后&#34;只是一个布尔值告诉我们是否要向后或向前,从而设置正确的索引来开始。

答案 2 :(得分:0)

这是一个单for - 循环的解决方案。

#include <iostream>
using namespace std;

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

int main() {
  for (int x=0; x<16; x++) {
    cout << matrix[x/4][ x%4 * ((x/4+1)&1) + (3-x%4)*((x/4)&1) ] << "  ";
    if (x%4==3) cout << endl;
  }
  return 0;
}

第一个[]只是通过除以4 - >给出行。 i/4。 第二个[]以2个步骤为列提供。它除了4 - >之后需要提醒。 x%4如果是偶数行,则乘以1 - &gt; (x/4+1)&1然后按相反的顺序添加提醒 - &gt; 3-x%4如果是奇数行,则乘以1 - &gt; (x/4)&1

答案 3 :(得分:0)

一种更简单易懂的方法

#include <iostream>
using namespace std;
int main() {
    // your code goes here
    int matrix[4][4] = { { 0,1,2,3}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}};
    bool forward = true;
    int j;
    for(int i = 0,k=0;i<4;i++)
    {
        if(forward)
        {
            for(j=0;j<4;j++)
            {
                cout<<matrix[i][j]<<" ";
            }
            cout<<endl;
            forward = false;
        }
        else
        {
            for(j=3;j>=0;j--)
            {
                cout<<matrix[i][j]<<" ";
            }
            cout<<endl;
            forward = true;
        }
    }
    return 0;
}
相关问题