2013-03-15 79 views

回答

8

這個問題不是很適合這個網站,因爲它似乎不是關於實際的代碼。

但是,我會反過來一槍。

當然,您可以通過回溯算法獲得所有可能的解決方案。記住一個回溯算法如何工作的:

while(there are still guesses available) 
    make a guess 
    solve the puzzle with the guess 
    if there was a solution then record the solution and quit the loop. 
    cross the guess off the list of possible guesses 
if you recorded a solution then the puzzle is solvable.

如果你希望所有的解決方案則只需修改算法:

while(there are still guesses available) 
    make a guess 
    solve the puzzle with the guess 
    if there was a solution then record the solution. Don't quit. 
    cross the guess off the list of possible guesses 
if you recorded any solution then the puzzle is solvable.

順便說一句,我寫了一系列博客文章上使用圖形在C#中解決數獨色彩回溯算法;它可能是你的興趣:

http://blogs.msdn.com/b/ericlippert/archive/tags/graph+colouring/

在這段代碼中,你會看到一行:

return solutions.FirstOrDefault(); 

「解決方案」包含枚舉所有的解決方案的查詢。我只想要第一個這樣的解決方案,所以這就是我所要求的。如果您想要每個解決方案,只需重寫該程序,以便它不會調用FirstOrDefault。有關注釋,請參閱下面的註釋。

+0

如果內存服務於撰寫博客文章以提供一種有效的解決方案而非全部。可以修改它以返回所有解決方案,但這就是這個問題所要求的......儘管這是一個很棒的博客系列。 – Servy 2013-03-15 17:19:35

+0

@Servy:正確,但它是對代碼的簡單修改。回想一下,我產生了一個表示所有解決方案的查詢,然後調用'return solutions.FirstOrDefault();' - 如果你想要每個解決方案,只需從那裏取出'FirstOrDefault'並返回'solutions'。 – 2013-03-15 17:23:03

+0

我記得當我第一次閱讀系列時,我做了修改,把所有的操作都作爲練習返回,它不是那麼簡單,主要是因爲你不再需要'null'值而是具有空集合,然後依賴於空檢查的算法的其他方面需要改變,並且你不希望多次迭代序列,所以總的來說它不是*超*難,但它不僅僅是簡單刪除'FirstOrDefault'。 – Servy 2013-03-15 17:26:35