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.
97 lines
2.6 KiB
97 lines
2.6 KiB
#include <stdio.h>
|
|
|
|
#define SIZE 9
|
|
void printMatrix(int matrix[SIZE][SIZE]) {
|
|
int i,j;
|
|
for (i = 0; i < SIZE; i++) {
|
|
for (j = 0; j < SIZE; j++) {
|
|
printf("%d ", matrix[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
}
|
|
int checkRow(int matrix[SIZE][SIZE], int row) {
|
|
int seen[SIZE + 1] = {0};
|
|
int col;
|
|
for (col = 0; col < SIZE; col++) {
|
|
int num = matrix[row][col];
|
|
if (num != 0) {
|
|
if (seen[num]) {
|
|
printf("The number %d in the row %d has been used!\n", num, row + 1);
|
|
return 0;
|
|
}
|
|
seen[num] = 1;
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
int checkCol(int matrix[SIZE][SIZE], int col) {
|
|
int seen[SIZE + 1] = {0};
|
|
int row;
|
|
for (row = 0; row < SIZE; row++) {
|
|
int num = matrix[row][col];
|
|
if (num != 0) {
|
|
if (seen[num]) {
|
|
printf("The number %d in the col %d has been used!\n", num, col + 1);
|
|
return 0;
|
|
}
|
|
seen[num] = 1;
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
int checkBlock(int matrix[SIZE][SIZE], int block) {
|
|
int seen[SIZE + 1] = {0};
|
|
int startRow = (block / 3) * 3;
|
|
int startCol = (block % 3) * 3;
|
|
int i,j;
|
|
for (i = 0; i < 3; i++) {
|
|
for (int j = 0; j < 3; j++) {
|
|
int num = matrix[startRow + i][startCol + j];
|
|
if (num != 0) {
|
|
if (seen[num]) {
|
|
printf("The number %d in the block %d has been used!\n", num, block + 1);
|
|
return 0;
|
|
}
|
|
seen[num] = 1;
|
|
}
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
int main() {
|
|
int matrix[SIZE][SIZE] = {
|
|
{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");
|
|
printMatrix(matrix);
|
|
for (int i = 0; i < SIZE; i++) {
|
|
if (!checkRow(matrix, i)) {
|
|
printf("False: Invalid initial Sudoku matrix!\n");
|
|
return 0;
|
|
}
|
|
if (!checkCol(matrix, i)) {
|
|
printf("False: Invalid initial Sudoku matrix!\n");
|
|
return 0;
|
|
}
|
|
}
|
|
for (int block = 0; block < SIZE; block++) {
|
|
if (!checkBlock(matrix, block)) {
|
|
printf("False: Invalid initial Sudoku matrix!\n");
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
printf("True: Valid initial Sudoku matrix!\n");
|
|
return 0;
|
|
}
|