遍历二维数组先按行再按列

4

我正在寻找一种方法来遍历一个2D的n行m列的int数组(int[col][row]),首先按行遍历(简单部分),然后按列遍历,在Java中。以下是按行遍历的代码,有没有一种方法可以按列遍历?

for(int i = 0; i < display.length; i++){
            for (int j = 0; j < display[i].length; j++){
                if (display[i][j] == 1)
                    display[i][j] = w++;
                else w = 0;
            }
        }

变宽的列? - JustinKSU
1
如果你在循环内将display[i][j]更改为display[j][i]会怎样? - Thrash Bean
不要使用可变宽度列。如果您更改了它,因为它是n乘m的网格,它会改变方向,这是不可取的。 - AlexK
如果以下任何一个答案对您有用,请接受它。 - JustinKSU
5个回答

5

由于您使用了二维数组作为矩阵,因此我们可以假设在整个矩阵中每行的长度都相同(即每行的列数相同)。

//So, you can treat display[0].length as the number of columns.

for(int col=0; col<display[0].length; col++)
{
   for(int row=0; row<display.length; row++)
   {
      //your code to access display[row][col]
   }
}

希望这能有所帮助!

这似乎是有道理的。谢谢! - AlexK
是的,就像hexafraction所提到的那样,Java不会将多维数组视为矩形。如果你能够安全地假设你的数组确实是一个矩阵,那么以上代码才能够使用。 - garyF

4
这里有一种方法,当行具有与该列相同的数量的列时,它将按列打印。
String[][] twoDArray = new String[][] {
        new String[] {"Row1Col1", "Row1Col2", "Row1Col3"},
        new String[] {"Row2Col1", "Row2Col2"},
        new String[] {"Row3Col1", "Row3Col2", "Row3Col3", "Row3Col4"}
};

boolean recordFound = true;
int colIndex = 0;
while(recordFound) {
    recordFound = false;
    for(int row=0; row<twoDArray.length; row++) {
        String[] rowArray = twoDArray[row];
        if(colIndex < rowArray.length) {
            System.out.println(rowArray[colIndex]);
            recordFound = true;
        }
    }
    colIndex++;
}

输出结果为:

Row1Col1
Row2Col1
Row3Col1
Row1Col2
Row2Col2
Row3Col2
Row1Col3
Row3Col3
Row3Col4

1
由于Java数组是嵌套的而不是矩形多维数组,因此这并不是一件很“自然”的事情。例如,以下操作是可能的:
[ ][ ][ ]
[ ][ ]
[ ][ ][ ][ ][ ]

其中[ ]代表一个元素。

垂直遍历并不是一种非常"自然"或高效的操作。但是,你可以通过遍历列,直到数组长度的最大值,避免使用显式检查或(更糟糕的是)静默丢弃ArrayOutOfBounds异常来解决数组越界问题。

编辑:在矩形情况下,只需交换两个循环。无论使用哪一行的长度都没有关系。


我明白你的意思,但在这种特定情况下,我正在处理一个矩形2D数组 :) - AlexK
如果长度已知,则只需反转您的for循环。您始终可以根据第一列的长度来执行此操作。请参见garyF的答案。我的答案处理了hex所指的情况。 - JustinKSU

0
static void columnFirst(List<List<Integer>> matrix) {
    int max = 0;
    for (int i = 0; i < matrix.size(); i++) {
        max = Math.max(max, matrix.get(i).size());
    }


    for (int i = 0; i < max; i++) {
        for (int j = 0; j < matrix.size(); j++) {
            if (matrix.get(j).size() > i)
                System.out.print(matrix.get(j).get(i) + " ");
        }
        System.out.println();
    }
}

输入数组

{{1, 2, 3, 4, 5, 6},
 {1, 2, 3},
 {1, 2, 3, 4, 5},
 {1},
 {1, 2, 3, 4, 5, 6, 7, 8, 9}}

输出:

1 1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 
5 5 5 
6 6 
7 
8 
9 

0
/* 
Assume that the length of the col[0] will be the same for all cols. 
Notice: that we are access salaries[j] for each iteration of j while
[i] same the same. 
*/

public void printColsValues() {
    for(int i = 0; i < array[0].length; i++) {
        for(int j = 0; j < array.length; j ++) {
            System.out.println(arr[j][i]);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接