JAVA:如何创建一个蛇形矩阵

时间:2012-11-23 12:34:12

标签: java arrays matrix

您好我正在尝试使用2D数组在控制台上创建矩阵。想法是输出应该像这样:

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

有没有人知道如何做到这一点?

3 个答案:

答案 0 :(得分:2)

你可以从矩阵中猜出

很少的东西: -

  • 首先,您必须首先遍历列的所有行,然后才能转到下一列

  • 其次,您需要在每次迭代时在downwardsupwards方向之间切换

  • 因此,您需要两个嵌套for循环,以迭代特定列的行。一个将从row 0 to max - 1开始,下一个将从row = max - 1 to 0开始。

  • 现在,为了交替迭代方向,您可以使用布尔变量,并在内循环的每次迭代完成后切换它。

  • 每个循环都需要包含在if-else内。它们都将在某种条件下执行。如果boolean downwards = false;,则向上移动将执行,反之亦然。

  • 在每次迭代中,使用整数计数器填充当前单元格,您必须使用1进行初始化,并在每次填充后将其递增。


伪代码: -

    // Initialize variables row, col, and count = 1

    boolean goDown = true;

    int[][] matrix = new int[row][col];  // declare matrix

    for i = 0 to col:
        if (goDown)
            for j = 0 to row:  // Move in downwards direction
                assign count++ to matrix[j][i] 
                // assign to `[j][i]` because, we have to assign to rows first

            goDown = false;    // Toggle goDown

        else
            for j = row - 1 to 0:  // Move in upwards direction
                assign count++ to matrix[j][i] 

            goDown = true;  // toggle goDown

    }

答案 1 :(得分:0)

只是一些伪代码,希望它有所帮助,并为您提供一些开始。

boolean goUp = false;
boolean goDown = true;
size = 4;
matrix[size][size];
k = 0; 
l =0;

loop i->0 i < size*size i++
  matrix[l][k] = i;

  if(l==size and goDown)
    goDown = false;
    goUp = true;
    k++;
  else if(l==0 and goUp)
    goDown = true;
    goUp = false;
    k++;
  else
    l = l+ (1*goDown?1:-1);
end loop;

答案 2 :(得分:0)

最后在你的帮助下,仔细研究了多维数组的工作方式后,我解决了现在看起来很简单的问题。

int a = 4;
    int b = 4;
    int c = 1;
    boolean direction = true;
    int[][] arrey = new int[a][b];
    for (int y = 0; y <= b - 1; y++) {
        if (direction) {
            for (int x = 0; x <= a - 1; x++) {
                arrey[x][y] = c;
                c++;
            }
            direction = false;
        } else {
            for (int x = a - 1; x >= 0; x--) {
                arrey[x][y] = c;
                c++;
            }
            direction = true;
        }
    }

    for (int x = 0; x <= a - 1; x++) {
        for (int y = 0; y <= b - 1; y++) {
            System.out.print("["+arrey[x][y]+"]");
        }
        System.out.println("");
    }