Thread: Recursive for loop causing problems

1. Member Join Date
Oct 2010
Posts
8
Rep Power
0 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:-

Java 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  Reply With Quote

2. Senior Member Join Date
Aug 2010
Posts
127
Rep Power
0 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?  Reply With Quote

3. Member Join Date
Oct 2010
Posts
8
Rep Power
0 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.  Reply With Quote Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•