You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.6 KiB

#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;
}
}