这是我使用递归回溯的C数独求解器,带有在线帮助代码。程序很小,拼图的分支存储在堆栈中,它向前移动添加新的拼图,如果它找不到位置的解决方案,它将返回到前一个分支并继续。
虽然这适用于找到1个解决方案,但我试图调整它以打印每个解决方案。其他条款/ *解决方案找不到更多空的块! * /是该功能的结束,我尝试使用各种(行,列)作为sudokuSolver()返回,但似乎无法正确地继续打印所有解决方案。
代码:
#include <stdio.h>
#include <string.h>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
int rowStart = (row/3) * 3;
int colStart = (col/3) * 3;
int i, j;
for(i=0; i<9; ++i) {
if (puzzle[row][i] == num)
return 0;
if (puzzle[i][col] == num)
return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num)
return 0;
}
return 1;
}
int solveSudoku(int puzzle[][9], int row, int col)
{
int i;
if (row<9 && col<9) {
if(puzzle[row][col] != 0) {
if ((col+1) < 9)
return solveSudoku(puzzle, row, col+1);
else if ((row+1) < 9)
return solveSudoku(puzzle, row+1, 0);
else /*SOLUTION FOUND AS NO MORE EMPTY BLOCKS!*/
return 1;
}
else {
for(i=0; i<9; ++i) {
if(isAvailable(puzzle, row, col, i+1)) {
puzzle[row][col] = i+1;
if ((col+1) < 9){
if (solveSudoku(puzzle, row, col +1))
return 1;
else
puzzle[row][col] = 0;
}
else if ((row+1) < 9) {
if (solveSudoku(puzzle, row+1, 0))
return 1;
else
puzzle[row][col] = 0;
}
else
return 1;
}
}
}
return 0;
}
else {
return 1;
}
}
int main()
{
int sudoku_arr[9][9] = {
{8,0,0,6,0,0,9,0,5},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,2,0,3,1,0},
{0,0,7,3,1,8,0,6,0},
{2,4,0,0,0,0,0,7,3},
{0,0,0,0,0,0,0,0,0},
{0,0,2,7,9,0,1,0,0},
{5,0,0,0,8,0,0,3,6},
{0,0,3,0,0,0,0,0,0}
};
if (solveSudoku(sudoku_arr, 0, 0)) { //Solve sudoku puzzle
printf("\nSudoku solved:\n");
int row, col;
for(row=0; row<9; row++) {
for(col=0; col<9; col++) {
printf("%d ", sudoku_arr[row][col]);
}
printf("\n");
}
return 0;
}
else {
printf("\nNo sudoku solution");
return -1;
}
}
现在虽然这解决了第一个解决方案:
Sudoku solved:
8 1 4 6 3 7 9 2 5
3 2 5 1 4 9 6 8 7
7 9 6 8 2 5 3 1 4
9 5 7 3 1 8 4 6 2
2 4 1 9 5 6 8 7 3
6 3 8 2 7 4 5 9 1
4 6 2 7 9 3 1 5 8
5 7 9 4 8 1 2 3 6
1 8 3 5 6 2 7 4 9
还有许多其他可能的解决方案,即 814637925325149687796825314957318462241956873638274591462793158579481236183562749 814637925325941687796825314957318462241569873638472591462793158579184236183256749 834671925125839647796425318957318462241956873368247591682793154579184236413562789 834671925125839647796524318957318462241956873368247591682793154519482736473165289 834671925125839647796524318957318462241965873368247591682793154519482736473156289
答案 0 :(得分:0)
sudoku_arr
通过引用传递。在solveSudoku ()
函数中设置值时,您将覆盖原始数组,因此当它尝试回溯时,阵列上不再有0
值的位置。
您真正想做的是在0
之前将值重置为solveSudoku ()
中的return 1;
。
此外,只要在返回之前没有空位置,您就会想要打印解决方案。
This可能会有所帮助。