当前位置: 首页 > >

解数独算法,用C语言递归实现

发布时间:

前几天在看离散数学及其应用第七版的时候,看到了数独的相关章节,就自己写了一个数独的解法,先记下来。生成数独的方法以后再写



#include

// 寻找下一个未填充的单元
int find_next_empty(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("
");
}
}
}

int do_resolve(int arr[9][9], int row, int col)
{
int i, j, n;

int next_row, next_col;

n = 0;
while(1) {
next_num:
++n;
if (n >= 10) break;

// 判断行重复
for (j = 0; j < 9; j++) {
if (arr[row][j] == n) {
goto next_num;
}
}

// 判断列重复
for (i = 0; i < 9; i++) {
if (arr[i][col] == n) {
goto next_num;
}
}

/* 判断所在小九宫格重复*/
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 next_num;
}
}
}

//该单元可以填充
arr[row][col] = n;
//如果9宫格已填满,完成,这里不考虑有多解的情况
if (!find_next_empty(arr, row, &next_row, &next_col)) {
return 1;
}
//否则继续填下一个未填充的格子
if (!do_resolve(arr, next_row, next_col)) {
arr[row][col] = 0;
continue;
} else {
return 1;
}
}

return 0;
}

void resolve_sudoku(int a[9][9])
{
int row, col;

find_next_empty(a, 0, &row, &col);
do_resolve(a, row, col);
}

int main(void)
{
int a[9][9] = {
8,0,0,0,0,0,0,0,0,
0,0,3,6,0,0,0,0,0,
0,7,0,0,9,0,2,0,0,
0,5,0,0,0,7,0,0,0,
0,0,0,0,4,5,7,0,0,
0,0,0,1,0,0,0,3,0,
0,0,1,0,0,0,0,6,8,
0,0,8,5,0,0,0,1,0,
0,9,0,0,0,0,4,0,0
};
resolve_sudoku(a);
print(a);

return 0;
}






友情链接: