c语言回溯算法数独,数独回溯算法

首先,我要声明这是大学的工作,所以我并没有要求别人为我编写代码,我只需要指出正确的方向即可。:)

好的,因此我需要编写一种算法来解决任意大小的(可解决的)数独板。我编写了一个递归函数,可以快速(〜1ms)求解任何9x9电路板,但是当我做较大的电路板(16x16)时,它很难解决。.我已经进行了20分钟的测试,它可以似乎无法解决。它可以解决简单的16x16难题,甚至可以解决空白的16x16电路板,所以我认为问题不在于尺寸。它更可能是我认为的算法。

无论如何,这是我程序的基本逻辑。

我有一个3D向量,可以存储每个正方形的可能值

当将值放置在正方形中时,会将其从周围的正方形,行和列的可能值中删除

那么我的求解功能基本上是:

bool solve() {

if (there are no unfilled squares)

return true

if (the board is unsolvable - there are empty squares that have no possible values)

return false

while (there are empty squares)

{

int squaresFilled = fillSquaresWithOnlyOneChoice(); //this method updates the possible results vector whenever it fills a square

if (squaresFilled == 0)

break;

}

//exhausted all of the 'easy' squares (squares with only one possible choice), need to make a guess

while (there are empty squares that have choices left) {

find the square with the least number of choices

if (the square with the least number of choices has 0 choices)

return false; //not solvable.

remove that choice from the 3D vector (vector that has the choices for each square)

make a copy of the board and the 3D choices vector

fill the square with the choice

if (solve())

return true; //we're done

restore the board and choices vector

//the guess didn't work so keep looping and make a new guess with the restored board and choices -- the choice we just made has been removed though so it won't get made again.

}

return false; //can't go any further

}

这有什么效率低下吗?有什么办法可以使它更好地工作吗?我猜想一个16x16的电路板要花这么长时间是因为它的决策树对于一个没有足够填充的电路板来说太大了。不过这很奇怪,因为9x9电路板可以解决得很快。

任何想法或建议都绝对很棒。如果有任何我想念的信息,也请告诉我!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值