2016-12-17 150 views
0

我正在编写Sudoku解算器,我的老师建议我使用3d数组,因为我从来没有使用过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; 
+0

提示:'board.length'会给你9 ...如果你使用'board [0]'给你一个'int [] []'。如果你知道如何处理二维数组,那么你应该很好... –

回答

2

可以使用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]); 
      } 
     } 
    } 
} 

然而,数独游戏,你并不需要一个三维阵列。二维数组就足够了。

+0

它的工作原理,但我觉得这样的代码不可读。为什么3D阵列?哪一个是宽度,哪个是高度,第二个是什么?等等......我会把它包装在一些自我评论的抽象层中。但是,这是迭代3D数组问题的正确答案。 – PiotrK

2
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]); 
      } 
     } 
    } 
} 
0

我假设你的三维阵列代表的数独如下: 的“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]); 
     } 
    } 
} 

,不解决这一切为您服务。