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電路板可以解決得很快。
任何想法或建議都絕對很棒。如果有任何我想念的信息,也請告訴我!
總結
以上是生活随笔為你收集整理的c语言回溯算法数独,数独回溯算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 硬盘整数分区计算方法(精确硬盘分区算法)
- 下一篇: 位图转换矢量图软件