C语言递归解决数独
运行程序,依次输入数独中的81个数,数独中没有数字的地方输入0,感觉需要输入那么多数太麻烦了,请大家指导如何改的简单一点。
- #include<stdio.h>
- #include<stdlib.h>
- #define DEBUG
- int shukudo[9][9];
- typedef struct shudo{
- int x;
- int y;
- struct shudo * next;
- }shukudo_ptr;
- int count = 0;
- void display_shukudo();
- int check_right(shukudo_ptr*,int);
- void solution(shukudo_ptr *empty_ptr)
- {
- if(!empty_ptr)
- {
- display_shukudo();
- return;
- }
- for(int i = 1; i < 10; ++i)
- {
- if(check_right(empty_ptr,i))
- {
- shukudo[empty_ptr->x][empty_ptr->y] = i;
- solution(empty_ptr->next);
- }
- shukudo[empty_ptr->x][empty_ptr->y] = 0;
- }
- }
- int check_right(shukudo_ptr *empty_ptr,int n)
- {
- for(int i = 0; i < 9; ++i)
- {
- if(shukudo[empty_ptr->x][i] == n)
- {
- return 0;
- }
- }
- for(int i = 0; i < 9; ++i)
- {
- if(shukudo[i][empty_ptr->y] == n)
- {
- return 0;
- }
- }
- int start_x = empty_ptr->x / 3 * 3;
- int start_y = empty_ptr->y / 3 * 3;
- for(int i = start_x; i < start_x + 3; ++i)
- {
- for(int j = start_y; j < start_y + 3; ++j)
- {
- if(shukudo[i][j] == n)
- {
- return 0;
- }
- }
- }
- return 1;
- }
- void display_shukudo()
- {
- ++count;
- printf("solution %d\n",count);
- for(int i = 0; i < 9; ++i)
- {
- for(int j = 0; j < 9; ++j)
- {
- printf("%d ",shukudo[i][j]);
- }
- printf("\n");
- }
- printf("\n\n");
- }
- int main(void)
- {
- shukudo_ptr *empty_ptr = NULL;
- shukudo_ptr *operate = NULL;
- shukudo_ptr *last = NULL;
- for(int i = 0; i < 9; ++i)
- {
- for(int j = 0; j < 9; ++j)
- {
- printf("(%d,%d): ",i,j);
- scanf("%d",&shukudo[i][j]);
- if(shukudo[i][j] == 0)
- {
- operate = (shukudo_ptr*)malloc(sizeof(shukudo_ptr));
- operate->x = i;
- operate->y = j;
- operate->next = NULL;
- if(!empty_ptr)
- {
- empty_ptr = operate;
- last = empty_ptr;
- }
- else
- {
- last->next = operate;
- last = operate;
- }
- }
- }
- }
- solution(empty_ptr);
- while(empty_ptr)
- {
- operate = empty_ptr;
- empty_ptr = empty_ptr -> next;
- free(operate);
- }
- return 0;
- }
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20