簡體   English   中英

JAVA:如何創建一個蛇形矩陣

[英]JAVA : How to create a snake shape matrix

嗨,我正在嘗試使用2D數組在控制台上創建矩陣。 想法是輸出應該像這樣:

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

有沒有人知道如何做到這一點?

你可以從矩陣中猜到幾件事情 : -

  • 首先,在移動到下一列之前,必須首先遍歷列的所有行

  • 其次,您需要在每次迭代時在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

    }

只是一些偽代碼,希望它有所幫助,並為您提供一些開始。

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;

最后在你的幫助下,仔細研究了多維數組的工作方式后,我解決了現在看起來很簡單的問題。

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("");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM