您的位置:首页 > 编程语言 > C#

C# 解数独程序 注释详细

2012-10-24 10:12 260 查看
想写这个程序源于芬兰的某数学家设计出了个号称史上最难的数独,本来想自己算算,可惜自己真的算不出来。于是便想写个程序把结果解出来~~图如下所示

源程序下载地址:

百度网盘:http://pan.baidu.com/share/link?shareid=84739&uk=1460631569

CSDN下载:http://download.csdn.net/detail/mqlccl2008/4670903



简单讲讲思路,贴一些关键代码,方便懒得下载的朋友

我把数独中每个格子设置一个关联的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什么什么之类的东西。后来发现竟然代码只有这么短……


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

顺便贴个程序也没原图吧



当然了~~其他数独也能解哦~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: