Recursive for loop causing problems
Hi
I'm trying to create a program which recursively solves Sudoku puzzles. My program works for most puzzles, by reading in the file, calling the solve method, and if it is not complete, guesses a number, and calls itself. If the number entered makes an illegitimate puzzle, it returns to the previous call. The way it guesses a number is through a for loop, which runs through 1-9, and if it is a legitimate guess, it calls the solve method. If, on exiting the for loop, it is an illegal guess, the return statement is called.
The problem is that if the final guess of the for loop is legal at that time, it doesn't return to this cell. Any ideas on how to fix this?
Here is the solve method:-
Code:
public void solve()
{
z++;
// ps.println("Recursion level = " + z);
if(!checkLegitimatePuzzle())
{
System.out.println("Not legitimate");
}
if((checkWin()) && (checkLegitimatePuzzle()))
{
System.out.println("Your puzzle has been solved");
}
else
{
if(!checkWin())
{
for(int b = 0; b < squares.length; b++)
{
if(squares[b].getNumber() == 0)
{
for(int q = 1; q < 10; q++)
{
squares[b].setNumber(q);
System.out.println("b = " + b + " is set to " + q);
if(checkLegitimatePuzzle())
{
System.out.println("Legit b = " + b + " q = " + q);
solve();
if(checkWin())
{
break;
}
}
}
if(!checkLegitimatePuzzle())
{
System.out.println("setting to 0");
squares[b].setNumber(0);
return;
}
}
}
}
}
}
Squares is an 81 length array of my square class, which holds a number.
checkWin and checkLegitimatePuzzle, are methods to check if the puzzle is complete, and if it is legitimate, respectively.
Thanks