#include <stdio.h> // 寻找下一个未填充的单元 int findNextEmpty(int arr[9][9], int startRow, int *row, int *col) { int i, j; for (i = startRow; i < 9; i++) for (j = 0; j < 9; j++) if (arr[i][j] == 0) { *row = i; *col = j; return 1; } return 0; } //按行输出 void print(int a[9][9]) { int i, j; for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { printf("%2d", a[i][j]); if (j == 8) printf("\n"); } } } //检查是否重合 int resolve(int arr[9][9], int row, int col) { int i, j, n; int nextRow, nextCol; n = 0; while (1) { nextNum: ++n; if (n >= 10) break; // 检测所在行重复 for (j = 0; j < 9; j++) { if (arr[row][j] == n) { goto nextNum; } } // 检测所在列重复 for (i = 0; i < 9; i++) { if (arr[i][col] == n) { goto nextNum; } } /* 检测所在小九宫格重复*/ int x = (row / 3) * 3; int y = (col / 3) * 3; for (i = x; i < x + 3; i++) { for (j = y; j < y + 3; j++) { if (arr[i][j] == n) { goto nextNum; } } } //该单元可以填入 arr[row][col] = n; //如果9宫格已填满,完成,这里未考虑有多解的情况 if (!findNextEmpty(arr, row, &nextRow, &nextCol)) { return 1; } //否则继续填下一个未填充的格子 if (!resolve(arr, nextRow, nextCol)) { arr[row][col] = 0; continue; } else { return 1; } } return 0; } void resolveSudoku(int a[9][9]) { int row, col; findNextEmpty(a, 0, &row, &col); resolve(a, row, col); } int main(void) { int a[9][9] = { 9, 0, 0, 0, 5, 0, 0, 6, 0, 0, 2, 0, 0, 7, 0, 1, 0, 0 , 3, 0, 0, 1, 0, 2, 0, 4, 0 , 7, 0, 3, 8, 0, 0, 5, 2, 9 , 0, 0, 0, 3, 4, 5, 0, 0, 0 , 5, 1, 6, 0, 0, 9, 4, 0, 3 , 0, 5, 0, 2, 0, 8, 0, 0, 6 , 0, 0, 7, 0, 9, 0, 0, 1, 0 , 0, 3, 0, 0, 1, 0, 0, 0, 4 }; resolveSudoku(a); print(a); return 0; }
[此贴子已经被作者于2018-3-3 10:45编辑过]