Recursion not stopping after return - Sudoku Solver

  • Thread starter Thread starter salmon27
  • Start date Start date
S

salmon27

Guest
I am writing a Sudoku solver in Visual c# using a recursive backtracking algorithm. In my recursive solve method, the base case is checking if the board (an integer double array) is full. If the board is found to be full, it should return. I also made a message box pop up displaying the board as soon as the base case is met. The method works up to this point, because when the message box pops up the puzzle is successfully solved. However, when I dismiss the message box (or comment it out) the method continues to backtrack and turn all of the entries into zero, even after hitting the return statement.

Example:

Result before solve method:



006 097 004
230 810 006
700 002 080
087 201 040
400 000 002
020 403 610
050 700 009
900 036 078
600 950 300




Result right after calling solveSudoku(board) and the "Solved" message box pops up:



816 397 254
234 815 796
795 642 183
387 261 945
461 579 832
529 483 617
153 728 469
942 136 578
678 954 321


(the solve method correctly solves it at this point)


Result after I dismiss the message box and print the board once again:



006 097 004
230 810 006
700 002 080
087 201 040
400 000 002
020 403 610
050 700 009
900 036 078
600 950 300




(it has been changed back to the initial board)


Note: I plan on writing code to actually display the board later.

Code:

private void solveSudoku(int[,] intBoard)
{
int i = 0;
int j = 0;
List<int> possibilities;

if (checkFull(intBoard))
{
MessageBox.Show("Solved");
MessageBox.Show(printDoubleArray(intBoard));
return;

}
else
{


for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)

if (intBoard[x, y] == 0)
{
i = x;
j = y;
break;
}
else
{
continue;
}
}

possibilities = possibleNums(intBoard, i, j); // a list with the possible entries based
// on the row, column, and 3x3 grid

for (int x = 0; x < possibilities.Count; x++)
{
if (possibilities[x] != 0)
{
intBoard[i, j] = possibilities[x];
solveSudoku(intBoard); //recursion
}
}
intBoard[i, j] = 0;
}
}

When the message box comes out, that means the base case has been reached. Because of the return, I'm unsure why the method continues to run, but I'm guessing I don't fully understand the recursion. Why is it changing all of the values back to 0, and how do I stop it?

Continue reading...
 
Back
Top