我填補數獨板代碼如下所示: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)
它在哪裏出界?我看不到......
查看行數68,74 –
我查過了,不知道爲什麼它會超過第9位...... – szubansky
9出界 – BevynQ