[英]Iterate through a 3d array?
我正在编写数独求解器,我的老师建议我使用3d数组,因为我从未使用过3d数组。 我在弄清楚如何创建循环遍历行和遍历列的过程时遇到了麻烦。 您将如何去做?
编辑:我想出了如何遍历每三列/行,希望最终我应该能够完成其他六列/行,但是我是否朝着正确的方向前进?
int[][][] = board[9][3][3];
public boolean columnCheck(int[][][] board)
{
boolean filled = false;
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
System.out.println(board[i][j][0]);
}
}
return true;
}
public boolean rowCheck(int[][][] board)
{
boolean filled = false;
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
System.out.println(board[i][0][j]);
}
}
return true;
您可以使用3 for
循环遍历3D数组,例如:
public static void main(String[] args) throws FileNotFoundException {
int[][][] array = new int[9][3][3];
for(int i=0 ; i<array.length ; i++){
for(int j=0 ; j<array[i].length ; j++){
for(int k=0 ; k<array[i][j].length ; k++){
System.out.println("[" + i + "][" + j + "][" + k + "]:" + array[i][j][k]);
}
}
}
}
但是,对于数独游戏,您不需要3D阵列。 2D阵列就足够了。
public class Main {
public static void main(String[] args) {
int[][][] board = new int[3][3][9];
// Assume that first parameter is row
// The second is column
// Iterating through first row (board[0])
for (int i = 0; i < 3; i++) {
// i is col number
for (int j = 0; j < 9; j++) {
//j is block number
System.out.println(board[0][i][j]);
}
}
// Iterating through second column
for (int i = 0; i < 3; i++) {
// i is row number
for (int j = 0; j < 9; j++) {
// j is block number
System.out.println(board[i][1][j]);
}
}
}
}
我想您的3d数组按如下方式表示数独:“ 9”代表9个小的3x3块。 块的每一行的第一个“ 3”,每个块的列的第二个“ 3”。
这将给出以下内容:
array[0][x][y] | array[1][x][y] | array[2][x][y]
----------------------------------------------------
array[3][x][y] | array[4][x][y] | array[5][x][y]
----------------------------------------------------
array[6][x][y] | array[7][x][y] | array[8][x][y]
要遍历每一行,您可以执行以下操作:
// The first three rows
// You can probably figure out yourself how to do the last 6,
// and how to combine those 3 seperate sections
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
for (int k=0; j<3; k++) {
System.out.println(array[j][i][k]);
}
}
}
// The first three columns
for (int i=0; i<3; i++) {
for (int j=0; j<7; j+=3) {
for (int k=0; k<3; k++) {
System.out.println(array[j][k][i]);
}
}
}
我希望这会让您前进,而不会为您解决所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.