# Recursive for loop causing problems

• 02-22-2011, 01:30 PM
Catfish1
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()))
{
}

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
• 02-22-2011, 02:38 PM
imorio
So you go over all the squares in the puzzle using a for-loop AND go over all the squares of the puzzle using recursion?

btw: shouldn't you check if you are done (ie: won) before trying to solve the rest of the puzzle?
• 02-22-2011, 04:12 PM
Catfish1
Thanks, so should the going over all the squares be done outside of the solve method? I've also swapped the solve() and if(checkWon) around.