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.

129 lines
3.0 KiB

#include <stdio.h>
#include <stdbool.h>
// 打印数独函数
void x1(int m[9][9])
{
int i,j;
for(i=0;i<9;i++)
{
if(i%3==0)printf("-------------\n");
for(j=0;j<9;j++)
{
if(j%3==0)printf("|");
printf("%d",m[i][j]);
}
printf("|\n");
}
printf("-------------\n");
}
// 检查行是否有效
bool hang(int m[9][9], int i, int num) {
for (int j = 0; j < 9; j++) {
if (m[j][i] == num) {
return false;
}
}
return true;
}
// 检查列是否有效
bool lie(int m[9][9], int j, int num) {
for (int i = 0; i < 9; i++) {
if (m[i][j] == num) {
return false;
}
}
return true;
}
// 检查3x3子矩阵是否有效
bool o3(int board[9][9], int starti, int startj, int num) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[starti + i][startj + j] == num) {
return false;
}
}
}
return true;
}
// 检查某个位置是否可以放置某个数字
bool check(int m[9][9], int i, int j, int num) {
return hang(m, i, j) &&
lie(m, i, j) &&
o3(m, i - i % 3, j - j % 3, num);
}
// 解数独
bool solve(int m[9][9]) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (m[i][j] == 0) {
for (int num = 1; num <= 9; num++) {
if (check(m, i, j, num)) {
m[i][j] = num;
if (solve(m)) {
return true;
}
m[i][j] = 0; // 回溯
}
}
return false; // 无法填充,回溯
}
}
}
return true; // 数独已解
}
// 检查整个数独矩阵是否有效
bool judge(int m[9][9]) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (m[i][j] != 0) {
int num = m[i][j];
m[i][j] = 0;
if (!check(m, i, j, num)) {
printf("The number %d in the row %d has been used!\n", num, i + 1);
m[i][j] = num;
return false;
}
m[i][j] = num;
}
}
}
return true;
}
int main() {
int m[9][9] ={{8, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
printf("The original Sudoku matrix:\n");
x1(m);
if (judge(m)) {
printf("True: Valid initial Sudoku matrix!\n");
if (solve(m)) {
printf("The solution of Sudoku matrix:\n");
x1(m);
} else {
printf("No solution!\n");
}
} else {
printf("False: Invalid initial Sudoku matrix!\n");
printf("No solution!\n");
}
return 0;
}