C# 解数独程序 注释详细

1 篇文章 0 订阅
1 篇文章 0 订阅
想写这个程序源于芬兰的某数学家设计出了个号称史上最难的数独,本来想自己算算,可惜自己真的算不出来。于是便想写个程序把结果解出来~~图如下所示

源程序下载地址: 
百度网盘:http://pan.baidu.com/share/link?shareid=84739&uk=1460631569

简单讲讲思路,贴一些关键代码,方便懒得下载的朋友
我把数独中每个格子设置一个关联的List,然后在list中添加1到9这9个数字。然后如果在该行、列、九宫里面有该数字的话。就从这个list中删去。
其实对于一些简单的数独,做到上面这一步也就可以了,可惜上面这个数独,按照上面的方法全部处理之后也就只能填出21个左右的数字吧(记不清了解数独程序)。剩下的就只能猜了。人脑基本不够用,电脑就方便多了。
核心递归算法
private void Jisuan(List<int>[,] L, int r, int c)
        {
            List<int>[,] tempList = new List<int>[9, 9];
            CopyList(L, tempList);//这里重写copy方法的话更易于理解一些

            if (tempList[r, c].Count != 1)
            {
                List<int>[,] temptempList = new List<int>[9, 9];
                CopyList(tempList, temptempList);
                for (int i = 0; i < tempList[r, c].Count && !GetResult; i++)
                {
                    temptempList[r, c].Clear();
                    temptempList[r, c].Add(tempList[r, c][i]);

                    List<int>[,] temptemptempList = new List<int>[9, 9];
                    CopyList(temptempList, temptemptempList);
                    do cal(temptemptempList);
                    while (!checkEnd(temptemptempList));//直到count数不再改变
                    if (!HasCount0(temptemptempList))//不含有count为0的情况
                    {
                        //获得nextr和nextc
                        int nextr = 0; int nextc = 0;
                        GetNextRC(r, c, ref nextr, ref nextc);

                        if (nextr == 9 && nextc == 0)//到了最后一个节点
                        {
                            printout(temptemptempList);
                            GetResult = true;
                            return;
                        }
                        else
                            Jisuan(temptemptempList, nextr, nextc);
                    }
                }
            }
            else//tempList[r, c].Count == 1的情况
            {
                //获得nextr和nextc
                int nextr = 0; int nextc = 0;
                GetNextRC(r, c, ref nextr, ref nextc);

                if (nextr == 9 && nextc == 0)//到了最后一个节点
                {
                    printout(tempList);
                    GetResult = true;
                    return;
                }
                else
                    Jisuan(tempList, nextr, nextc);
            }
        }
如果想吐槽里面函数、变量名字的话……就使劲的喷吧~~因为这个博主本人能力有限,这个程序写了很多遍才写出来,各种名字都想遍了,最后英语单词实在不够用了,就只好上拼音了。变量也就有了temptemp什么什么之类的东西。后来发现竟然代码只有这么短……解数独程序

源程序里面里面注释挺多的,方便和博主一样的新手理解学习互相交流~~欢迎交流,如果喷,请轻喷~~
顺便贴个程序也没原图吧

当然了~~其他数独也能解哦~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值