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>
// <20><>ӡ<EFBFBD><D3A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
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");
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>Ч
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;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>Ч
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;
}
// <20><><EFBFBD><EFBFBD>3x3<78>Ӿ<EFBFBD><D3BE><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>Ч
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;
}
// <20><><EFBFBD><EFBFBD>ij<EFBFBD><C4B3>λ<EFBFBD><CEBB><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD>Է<EFBFBD><D4B7><EFBFBD>ij<EFBFBD><C4B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
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);
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
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; // <20><><EFBFBD><EFBFBD>
}
}
return false; // <20>޷<EFBFBD><DEB7><EFBFBD><EFBFBD><EFBFBD><E4A3AC><EFBFBD><EFBFBD>
}
}
}
return true; // <20><><EFBFBD><EFBFBD><EFBFBD>ѽ<EFBFBD>
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>Ч
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;
}