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.

166 lines
4.0 KiB

#include <stdio.h>
int sudoku[9][9];
void print_sudoku(int sudoku[9][9]) {
for (int i = 0; i < 9; i++) {
if (i % 3 == 0 && i != 0) {
printf("-------------------------\n");
}
for (int j = 0; j < 9; j++) {
if (j % 3 == 0 && j != 0) {
printf("| ");
}
printf("%d ", sudoku[i][j]);
}
printf("\n");
}
}
int is_sudoku(int sudoku[9][9]) {
for (int i = 1; i <= 3; i++)
{
int num[10] = { 0 };
for (int j = 1; j <= 3; j++)
{
for (int k = 0; k < 9; k++)
{
num[(sudoku[i * j - 1][k])]++;
if (num[(sudoku[i * j - 1][k])] >1 && sudoku[i * j - 1][k] != 0)
{
printf("False:Invalid initial Sudoku matrix!\n");
for (int a = (i - 1) * 3; a <= i * j - 1; a++)
{
for (int c = 0; c < 9; c++)
{
if (sudoku[a][c] == sudoku[i * j - 1][k])
{
printf("The number %d in the col %d has been used!\n", sudoku[i * j - 1][k], a + 1);
return 0;
}
}
}
}
}
}
for (int l = 1; l < 10; l++)
{
if (num[l] < 1)
{
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d has not been used\n", l);
return 0;
}
}
}
printf("True:Valid initial Sudoku matrix!\n");
return 1;
}
int findvalue(int sudoku[9][9], int i, int j)
{
int m, n, k;
int temp[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (k = 1; k < 10; k++)
{
if (temp[sudoku[i][k - 1]] == 0)
temp[sudoku[i][k - 1]] = sudoku[i][k - 1];
if (temp[sudoku[k - 1][j]] == 0)
temp[sudoku[k - 1][j]] = sudoku[k - 1][j];
}
for (m = 0; m < 3; m++)
for (n = 0; n < 3; n++)
if (temp[sudoku[i / 3 * 3 + m][j / 3 * 3 + n]] == 0)
temp[sudoku[i / 3 * 3 + m][j / 3 * 3 + n]] = sudoku[i / 3 * 3 + m][j / 3 * 3 + n];
for (k = 1; k < 10; k++)
if (temp[k] == 0)
{
temp[0]++;
m = k;
}
if (temp[0] == 0)
return -1;
else if (temp[0] == 1)
return m;
else
return 0;
}
int main() {
int flag;
int sudoku[9][9] = { {0, 3, 0, 0, 0, 7, 0, 0, 0},
{1, 2, 5, 0, 0, 9, 4, 0, 0},
{0, 7, 9, 1, 0, 0, 0, 3, 0},
{0, 0, 6, 0, 8, 0, 0, 9, 1},
{0, 0, 0, 9, 5, 1, 0, 0, 0},
{9, 1, 0, 0, 7, 0, 5, 0, 0},
{0, 9, 0, 0, 0, 5, 7, 4, 0},
{0, 0, 8, 7, 0, 0, 2, 6, 9},
{0, 0, 0, 4, 0, 0, 0, 5, 0} };
printf("The original Sudoku matrix:\n");
print_sudoku(sudoku);
if (!is_sudoku(sudoku))
{
printf("No solution!");
return 0;
}
if (is_sudoku(sudoku))
{
int i, j, temp, empty = 0;
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
if (sudoku[i][j] == 0)
empty++;
}
while (empty)
{
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
if (sudoku[i][j] == 0)
{
temp = findvalue(sudoku, i, j);
if (temp == -1)
{
printf("No solution\n");
return 1;
}
sudoku[i][j] = temp;
if (temp != 0)empty--;
}
}
}
}
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
printf("%d ", sudoku[i][j]);
printf("\n");
}
}
return 0;
}