From 2766ab23eec689d9effd78e590ac6e4a4187ba69 Mon Sep 17 00:00:00 2001 From: pns4qt5fo <2085596522@qq.com> Date: Sun, 29 Oct 2023 10:21:59 +0800 Subject: [PATCH] ADD file via upload --- solve.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 solve.c diff --git a/solve.c b/solve.c new file mode 100644 index 0000000..b31fa45 --- /dev/null +++ b/solve.c @@ -0,0 +1,89 @@ + +#include + +int sudoku[9][9]; + +//ÅжÏÐÐ +int in_row(int row, int num) { + for (int i = 0; i < 9; i++) { + if (sudoku[row][i] == num) { + return 1; + } + } + return 0; +} + +//ÅжÏÁÐ +int in_col(int col, int num) { + for (int i = 0; i < 9; i++) { + if (sudoku[i][col] == num) { + return 1; + } + } + return 0; +} + +//ÅжϹ¬ +int in_box(int row, int col, int num) { + int box_row = row / 3 * 3; + int box_col = col / 3 * 3; + for (int i = box_row; i < box_row + 3; i++) { + for (int j = box_col; j < box_col + 3; j++) { + if (sudoku[i][j] == num) { + return 1; + } + } + } + return 0; +} + + +int is_valid(int row, int col, int num) { + return !in_row(row, num) && !in_col(col, num) && !in_box(row, col, num); +} + + +int solve_sudoku(int row, int col) { + if (row == 9) { + return 1; + } + if (col == 9) { // ÐÐÒѾ­ÌîÍ꣬תµ½ÏÂÒ»ÐÐ + return solve_sudoku(row + 1, 0); + } + if (sudoku[row][col] != 0) { // µ±Ç°¸ñ×ÓÒѾ­ÓÐÊý×Ö£¬×ªµ½ÏÂÒ»¸ö¸ñ×Ó + return solve_sudoku(row, col + 1); + } + for (int num = 1; num <= 9; num++) { //ö¾Ù» + if (is_valid(row, col, num)) { + sudoku[row][col] = num; + if (solve_sudoku(row, col + 1)) { + return 1; + } + sudoku[row][col] = 0; // »ØËÝ + } + } + return 0; +} + +int main() { + // ÊäÈëÊý¶ÀÊý×é + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + scanf("%d", &sudoku[i][j]); + } + } + // Çó½âÊý¶À + if (solve_sudoku(0, 0)) { + // Êä³öÇó½â½á¹û + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + printf("%d ", sudoku[i][j]); + } + printf("\n"); + } + } else { + printf("No solution!\n"); + } + return 0; +} + }