|
|
|
|
#include "SudokuMatrix.h"
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @brief 检查在指定位置是否可以放置数字num
|
|
|
|
|
*
|
|
|
|
|
* @param sudoku 一个数独矩阵
|
|
|
|
|
* @param row 行数位置
|
|
|
|
|
* @param col 列数位置
|
|
|
|
|
* @param num 想要放置的数字
|
|
|
|
|
* @return true 数字可以在这里放置
|
|
|
|
|
* @return false 数字不可以在这里放置
|
|
|
|
|
*/
|
|
|
|
|
bool isSafe(SudokuMatrix *sudoku, int row, int col, int num) {
|
|
|
|
|
// 检查行
|
|
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
|
|
if (sudoku->matrix[row][i] == num) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 检查列
|
|
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
|
|
if (sudoku->matrix[i][col] == num) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 检查九宫格
|
|
|
|
|
int startRow = row - row % 3;
|
|
|
|
|
int startCol = col - col % 3;
|
|
|
|
|
for (int i = 0; i < 3; i++) {
|
|
|
|
|
for (int j = 0; j < 3; j++) {
|
|
|
|
|
if (sudoku->matrix[i + startRow][j + startCol] == num) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @brief 使用回溯和递归方法解决数独
|
|
|
|
|
* 这是实际解决数独的函数,没有完整性检查之类的东西
|
|
|
|
|
*
|
|
|
|
|
* @param matrix 待求解的数独。这个数独的内容会改变。
|
|
|
|
|
* @return true 数独被成功求解
|
|
|
|
|
* @return false 数独求解失败
|
|
|
|
|
*/
|
|
|
|
|
bool _SolveMatrix(SudokuMatrix* matrix){
|
|
|
|
|
for (int row = 0; row < 9; row++) {
|
|
|
|
|
for (int col = 0; col < 9; col++) {
|
|
|
|
|
if (matrix->matrix[row][col] == 0) {
|
|
|
|
|
for (int num = 1; num <= 9; num++) {
|
|
|
|
|
if (isSafe(matrix, row, col, num)) {
|
|
|
|
|
matrix->matrix[row][col] = num;
|
|
|
|
|
if (_SolveMatrix(matrix)) {
|
|
|
|
|
return true; // 已找到解决方案
|
|
|
|
|
}
|
|
|
|
|
matrix->matrix[row][col] = 0; // 回溯
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false; // 没有解决方案
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true; // 所有格子都已填满,找到解决方案
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
bool SolveMatrix(SudokuMatrix *matrix, SudokuMatrix *result){
|
|
|
|
|
// 检查可求解性
|
|
|
|
|
if (!JudgeMatrix(matrix)){
|
|
|
|
|
printf("No solution!\n");
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 复制矩阵内容
|
|
|
|
|
if (matrix != result){
|
|
|
|
|
for (int i=0;i<9;i++){
|
|
|
|
|
for (int j=0;j<9;j++){
|
|
|
|
|
result->matrix[i][j] = matrix->matrix[i][j];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 进行求解
|
|
|
|
|
bool result_bool = _SolveMatrix(result);
|
|
|
|
|
if (result_bool){
|
|
|
|
|
printf("The solution of Sudoku matrix:\n");
|
|
|
|
|
PrintMatrix(result);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
else{
|
|
|
|
|
printf("No solution!\n");
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|