我填充数独板的代码如下:
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();
}
}
&#13;
根据数独游戏拼图规则,它使用回溯算法来检查数字的位置是否良好。 它会引发错误:
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 :(得分:1)
这个区块看起来不对:
if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}
我怀疑你想要这个:
if(row==9) {
row = 0;
if(++col == 9)
return true;
}
答案 1 :(得分:0)
col ++递增col,但返回旧值。您可能打算使用++ col,它返回新值。 (见Java: Prefix/postfix of increment/decrement operators?)
在您的代码中,当调用fillBoard(8, 8, grid)
时,col增加到9,但(col++ == 9)
被评估为false,因为col ++返回8.因此,您尝试访问grid [8] [9 ],这是抛出异常的时候。