首先对2d数组进行遍历,然后对列进行遍历

问题描述 投票:3回答:4

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

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;
            }
        }
java arrays 2d
4个回答
3
投票

这里是一种方法,如果该行有那么多列,则将按列打印。

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

3
投票

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

//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]
   }
}

希望这会有所帮助!


1
投票

由于Java数组是嵌套的而不是多维的矩形,因此发生的情况不是很“自然”。例如,以下可能是:

[ ][ ][ ]
[ ][ ]
[ ][ ][ ][ ][ ]

其中[ ]是元素。

垂直遍历不是一个非常“自然”或有效的操作。但是,您可以通过遍历最大数组长度的列来执行此操作,从而避免使用显式检查或(更邪恶的)静默丢弃ArrayOutOfBounds异常来避免数组超出范围的问题。

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


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 
© www.soinside.com 2019 - 2024. All rights reserved.