I am trying to write a program that will use backtracking to create a Sudoku solver. I have been able to create a black Sudoku grid and I can check to see if a move is a valid move. My program works fine until there are more than one choice of numbers for a square.
Problem: Will you look at my Solve method and see how I could modify it to backtrack, change the answer and move forward again. I gave the names of all of my other methods above and every one of those work.
Example input:
int board[ROWS][COLS] = {
{ 6, 0, 3, 0, 2, 0, 0, 9, 0 },
{ 0, 0, 0, 0, 5, 0, 0, 8, 0 },
{ 0, 2, 0, 4, 0, 7, 0, 0, 1 },
{ 0, 0, 6, 0, 1, 4, 3, 0, 0 },
{ 0, 0, 0, 0, 8, 0, 0, 5, 6 },
{ 0, 4, 0, 6, 0, 3, 2, 0, 0 },
{ 8, 0, 0, 2, 0, 0, 0, 0, 7 },
{ 0, 1, 0, 0, 7, 5, 8, 0, 0 },
{ 0, 3, 0, 0, 0, 6, 1, 0, 5 }
};
bool sudokuBoard::emptyCell(int i, int j);
bool sudokuBoard::isValidCol(int i, int j, int number);
bool sudokuBoard::isValidRow(int i, int j, int number);
bool sudokuBoard::isValidSquare(int i, int j, int number);
bool sudokuBoard::validMove(int i, int j, int number);
void sudokuBoard::solvePuzzle(int row, int col) {
for (int i = 1; i < 10; i++) {
if (validMove(row, col, i)) {
board[row][col] = i;
showBoard();
}
}
if (row < 8 && col < 8) {
if (col < 8) {
solvePuzzle(row, col + 1);
}
else {
col = 0;
solvePuzzle(row + 1, col);
}
}
}
Example current output:
6 5 3| 1 2 8| 4 9 0|
0 0 0| 0 5 0| 0 8 0|
0 2 0| 4 0 7| 0 0 1|
--------------------------------
0 0 6| 0 1 4| 3 0 0|
0 0 0| 0 8 0| 0 5 6|
0 4 0| 6 0 3| 2 0 0|
--------------------------------
8 0 0| 2 0 0| 0 0 7|
0 1 0| 0 7 5| 8 0 0|
0 3 0| 0 0 6| 1 0 5|
my program stops at the last 0 of the first row since there is no solution unless that previous 4 changes to a 7, the program terminates.