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;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值