I have this code here. It works fine when you're solving for a solution to a sudoku problem.
int solveBoard(int board[SIZE][SIZE], int rowPos, int colPos) {
int newValueToCheck, oldRowPos, oldColPos;
if (rowPos == SIZE) return 1;
if (board[rowPos][colPos] != 0) {
if (colPos == SIZE - 1) {
rowPos++;
colPos = 0;
} else colPos++;
if (solveBoard(board, rowPos, colPos) == 1) return 1;
return 0;
} for (newValueToCheck = 1; newValueToCheck <= SIZE; newValueToCheck++)
if (checkBoard(board, newValueToCheck, rowPos, colPos) == 1) {
board[rowPos][colPos] = newValueToCheck;
oldRowPos = rowPos;
oldColPos = colPos;
if (colPos == SIZE - 1) {
rowPos++;
colPos = 0;
} else colPos++;
if (solveBoard(board, rowPos, colPos) == 1) return 1;
rowPos = oldRowPos;
colPos = oldColPos;
board[rowPos][colPos] = 0;
}
return 0;
}
Only thing is, I'd like to get all possible answers. How will I modify this and get all the possible answers.
Don't backtrack the search when a solution has been found. So, make a simple recursive call at the place you try new values and ignore its return value:
solveBoard(board, rowPos, colPos);
and then you every solution at the tail of the recursion:
if (rowPos == SIZE) printSolution(); return 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.