2016-03-15 67 views
0

我填补数独板代码如下所示:Java数组越界 - 数独

public class SudokuBoard { 
 

 
    static int N = 9; 
 
    static int[][] grid = new int[N][N]; 
 

 
    static void printGrid() 
 
    { 
 
     for (int row = 0; row < N; row++) 
 
     { 
 
      for (int col = 0; col < N; col++) { 
 
       System.out.printf("%5d", grid[row][col]); 
 
      } 
 
      System.out.println("\n"); 
 
     } 
 
    } 
 

 
    private static boolean checkRow(int row, int num) 
 
    { 
 
     for(int col = 0; col < 9; col++) 
 
      if(grid[row][col] == num) 
 
       return false; 
 

 
     return true; 
 
    } 
 

 
    private static boolean checkCol(int col, int num) 
 
    { 
 
     for(int row = 0; row < 9; row++) 
 
      if(grid[row][col] == num) 
 
       return false; 
 

 
     return true; 
 
    } 
 

 
    private static boolean checkBox(int row, int col, int num) 
 
    { 
 
     row = (row/3) * 3; 
 
     col = (col/3) * 3; 
 

 
     for(int r = 0; r < 3; r++) 
 
      for(int c = 0; c < 3; c++) 
 
       if(grid[row+r][col+c] == num) 
 
        return false; 
 

 
     return true; 
 
    } 
 

 
    public static boolean fillBoard(int row, int col, int[][] grid) 
 
    { 
 
     if(row==9) 
 
     { 
 
      col = 0; 
 
      if(col++ == 9) 
 
       return true; 
 
     } 
 
     if(grid[row][col] != 0) 
 
      return fillBoard(row+1, col, grid); 
 
     for(int num = 1; num <=9; num++) 
 
     { 
 
      if(checkRow(row,num) && checkCol(col,num) && checkBox(row,col,num)){ 
 
       grid[row][col] = num; 
 
       if(fillBoard(row+1, col, grid)) 
 
        return true; 
 
      } 
 
     } 
 
     grid[row][col] = 0; 
 
     return false; 
 
    } 
 

 
    static public void main(String[] args){ 
 
     fillBoard(0, 0, grid); 
 
     printGrid(); 
 
    } 
 
}

它采用回溯的算法来检查数字的位置根据数独游戏谜题都不错规则。 它引发错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 
at SudokuBoard.fillBoard(SudokuBoard.java:68) 
at SudokuBoard.fillBoard(SudokuBoard.java:74) x9 
at SudokuBoard.main(SudokuBoard.java:84) 

它在哪里出界?我看不到......

+0

查看行数68,74 –

+0

我查过了,不知道为什么它会超过第9位...... – szubansky

+1

9出界 – BevynQ

回答

1

此块看上去错误:

if(row==9) 
    { 
     col = 0; 
     if(col++ == 9) 
      return true; 
    } 

我怀疑你想这样的:

if(row==9) { 
     row = 0; 
     if(++col == 9) 
      return true; 
    } 
+0

它的作品,非常感谢你:))) – szubansky

0

山坳++增量关口,但返回旧值。你可能打算使用++ col,它返回新的值。 (见Java: Prefix/postfix of increment/decrement operators?

在你的代码中,当fillBoard(8, 8, grid)被调用时,山坳增大到9,但(col++ == 9)被评估为假,因为山坳++返回8所以你再尝试接入电网[8] [9],其是抛出异常的时候。