I am programming a Sudoku solver in Java for a 9x9 grid.
I have methods for:
printing the grid
initializing the board with given values
testing for conflicts (if same number is in same line or 3x3 sub-grid)
a method to place the digits, one by one, which requires the most work.
Before I go into detail with that method, keep in mind that I have to use recursion to solve it, as well as backtracking (watch the applet here as an example http://www.heimetli.ch/ffh/simplifiedsudoku.html )
Also, I am solving this Sudoku by moving vertically downwards, starting from the top left, through the first column, and then through the second column, etc.
So far, I have the following:
public boolean placeNumber(int column){
if (column == SUDOKU_SIZE){ // we have went through all the columns, game is over
return true;
}
else
{
int row=0; //takes you to the top of the row each time
while (row < SUDOKU_SIZE) loops through the column downwards, one by one
{
if (puzzle[row][column]==0){ //skips any entries already in there (the given values)
puzzle[row][column]=1; //starts with one
while(conflictsTest(row,column)){ //conflictsTest is the method I wrote, which checks if the given parameters are in conflict with another number
puzzle[row][column] += 1;
}
//BACK TRACKING
placeNumber(column); //recursive call
}
else{
row++; // row already has a number given, so skip it
}
}
column++; // move on to second column
placeNumber(column);
}
return false; // no solutions to this puzzle
}
Where I labeled BACKTRACKING is where I believe the remainder of my code needs to go.
I thought up of something along the lines of:
- if the value is 10, set that value back to zero, go back a row, and increment that value by 1
That backtracking 'strategy' doesn't exactly work for several reasons:
what if the previous row, was a given value (aka I'm not supposed to increment it or touch it, but instead, go back to the last value that I placed there)
what if the previous value was a 9. and if I incremented that by 1, now we're at 10, which won't work.
Can someone please help me out?