使用回溯算法求解数独
核心算法:
int findNextValue(int rowIndex, int colIndex, int start) {
int index = findIndex(rowIndex, colIndex);// 找到所在的宫
for (int i = start; i < 9; i++) {
if (rule[0][rowIndex][i]) continue;
if (rule[1][colIndex][i]) continue;
if (rule[2][index][i]) continue;
return i;
}
return -1;
}
修改占用状态的函数changRule
void changeRule(int rowIndex, int colIndex, int style) {
int index = findSmallIndex(rowIndex, colIndex);
int value = sudoku[rowIndex][colIndex];
rule[0][rowIndex][value] = style;
rule[1][colIndex][value] = style;
rule[2][index][value] = style;
}
初始化函数
void initSudoku() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sudoku[i][j] = getchar() - '0' - 1;
flag[i][j] = ~sudoku[i][j] ? 0 : 1;
if (!flag[i][j]) changeRule(i, j, 1);
}
getchar();
}
}
主要求解函数
void solve(int rowIndex, int colIndex) {
if (colIndex == 9) {rowIndex++;colIndex = 0;}
while (rowIndex <= 8 && !flag[rowIndex][colIndex]) {
colIndex++;
if (colIndex == 9) {rowIndex++;colIndex = 0;}
}
if (rowIndex > 8) {show();return;}
while (~(sudoku[rowIndex][colIndex] = findNextValue(rowIndex, colIndex, sudoku[rowIndex][colIndex] + 1))) {
changeRule(rowIndex, colIndex, 1);
solve(rowIndex, colIndex + 1);
changeRule(rowIndex, colIndex, 0);
}
}