solveSudoku
函数从main()
函数中调用。
我编写了以下函数来解决数独问题:
#include <iostream>
#include <vector>
using namespace std;
int isvalid(char k, vector<vector<char> > A, int i, int j) { //Checking if putting the current element is not in same row, column or box
for(int t = 0; t < 9; t++) {
if(A[t][j] == k) //Checking jth column
return 0;
if(A[i][t] == k) //Checking ith row
return 0;
if(A[(i/3)*3+t/3][(j/3)*3+t%3] == k) //Checking current box
return 0;
}
return 1;
}
bool sudoku(vector<vector<char> > &A, int i, int j) {
if(i > 8 || j > 8) //If coordinates of the matrix goes out of bounds return true
return true;
if(A[i][j] == '.') {
for(char k = '1'; k <= '9'; k++) { //Trying to put every character possible
if(isvalid(k, A, i, j)) { //If putting character `k` doesn't makes the sudoku invaild put it
A[i][j] = k;
if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))//Check further if the sudoku can be solved with that configuration by going to the right block, down block and bottom-right block
return true;
else
A[i][j] = '.'; //Reset(If the sudoku can't be solved with putting `k` in `i, j` th index replace the '.' character at that position)
}
}
}
else {
if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))
return true;
}
return false;//This should trigger backtracking
}
void solveSudoku(vector<vector<char> > &A) {
sudoku(A, 0, 0);
}
int main() {
vector<vector<char> > A = {{'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'}}; //Input sudoku
solveSudoku(A);
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
cout<<A[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
输出
5 3 . . 7 . . . .
6 . . 1 9 5 . . .
. 9 8 . . . . 6 .
8 . . . 6 . . . 3
4 . . 8 . 3 . . 1
7 . . . 2 . . . 6
. 6 . . . . 2 8 .
. . . 4 1 9 . . 5
3 1 4 5 8 2 6 7 9
期望输出
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
在调用 `main()` 函数中的 `solveSudoku` 函数时,将输入的数独作为参数传递。它由字符 `1` 到 `9` 和代表空字符的点号 `.` 组成。`solveSudoku` 函数的工作是正确填写数独中的所有元素(在原地更改 `A` 中的值)。但我得到了错误的答案。给定的输入数独可解决。正如 Fezvez 所说,我认为我的算法问题在于这个语句 `if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))`。我认为,在使用有效字符填充单元格后,此语句应该递归地检查右侧、下方和对角线上的块是否也被填充。如果是,则数独已解决,应返回 true,但如果其中任何一个失败,它应该回溯。但是为什么它没有这样做呢?
i,j
是当前考虑的数独的坐标,我的代码中没有变量d
。 - Gyanshu