Reputation: 27
My code for filling sudoku board looks like this:
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();
}
}
It uses backtrack algorithm to check if placement of numbers are good according to sudoku game puzzle rules. It throws errors:
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)
Where is it out of bounds? I cannot see that...
Upvotes: 0
Views: 113
Reputation: 1966
This block looks wrong:
if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}
I suspect you want this:
if(row==9) {
row = 0;
if(++col == 9)
return true;
}
Upvotes: 1
Reputation: 401
col++ increments col, but returns the old value. You probably meant to use ++col, which returns the new value. (see Java: Prefix/postfix of increment/decrement operators?)
In your code, when fillBoard(8, 8, grid)
is called, col is increased to 9, but (col++ == 9)
gets evaluated to false, because col++ returns 8. So you then try to access grid[8][9], which is when the exception is thrown.
Upvotes: 0