From 301c571ee6ea8e462122138a39d96634383a8977 Mon Sep 17 00:00:00 2001 From: ptslgaequ <2728416244@qq.com> Date: Thu, 7 Nov 2024 19:05:05 +0800 Subject: [PATCH] ADD file via upload --- program3.c | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 program3.c diff --git a/program3.c b/program3.c new file mode 100644 index 0000000..473147d --- /dev/null +++ b/program3.c @@ -0,0 +1,114 @@ +#include +#include + +void printMatrix(int matrix[9][9]) { + for (int i = 0; i < 9; i++) { + if (i == 0 || i == 3 || i == 6) { + printf("|-----------------------|\n"); + } + for (int j = 0; j < 9; j++) { + if (j == 0 || j == 3 || j == 6) { + printf("| "); + } + if (matrix[i][j] == 0) { + printf(". "); + } + else { + printf("%d ", matrix[i][j]); + } + printf("|\n"); + } + printf("|-----------------------|\n"); + } +} + +// 检查行中数字1 - 9是否最多出现一次 +bool checkRows(int matrix[9][9]) { + for (int i = 0; i < 9; i++) { + int count[9] = {0}; + for (int j = 0; j < 9; j++) { + if (matrix[i][j] > 0 && matrix[i][j] <= 9) { + int num = matrix[i][j] - 1; + if (count[num] > 0) { + return false; + } + count[num]++; + } + } + } + return true; +} + +// 检查列中数字1 - 9是否最多出现一次 +bool checkColumns(int matrix[9][9]) { + for (int j = 0; j < 9; j++) { + int count[9] = {0}; + for (int i = 0; i < 9; i++) { + if (matrix[i][j] > 0 && matrix[i][j] <= 9) { + int num = matrix[i][j] - 1; + if (count[num] > 0) { + printf("The number %d in the col %d has been used!\n", matrix[i][j], j); + return false; + } + count[num]++; + } + } + } + return true; +} + +// 检查3x3子矩阵中数字1 - 9是否最多出现一次 +bool checkSubMatrices(int matrix[9][9]) { + for (int row = 0; row < 9; row += 3) { + for (int col = 0; col < 9; col += 3) { + int count[9] = {0}; + for (int i = row; i < row + 3; i++) { + for (int j = col; j < col + 3; j++) { + if (matrix[i][j] > 0 && matrix[i][j] <= 9) { + int num = matrix[i][j] - 1; + if (count[num] > 0) { + printf("The number %d in the block %d has been used!\n", matrix[i][j], (row / 3) * 3 + col / 3); + return false; + } + count[num]++; + } + } + } + } + } + return true; +} + +// 判断矩阵是否满足数独矩阵的定义 +bool isSudokuMatrix(int matrix[9][9]) { + if (!checkRows(matrix)) { + return false; + } + if (!checkColumns(matrix)) { + return false; + } + return checkSubMatrices(matrix); +} + +int main() { + printf("The original Sudoku matrix: \n"); + int matrix[9][9] = { + {5, 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} + }; + printMatrix(matrix); + bool result = isSudokuMatrix(matrix); + if (result) { + printf("True:Valid initial Sudoku matrix!\n"); + } else { + printf("False:Invalid initial Sudoku matrix!\n"); + } + return 0; +}