[英]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.