How to get all possible solutions using backtracking algorithm?

喜夏-厌秋 提交于 2021-02-10 04:59:25

问题


I'm using the backtracking algorithm described in this youtube video.

Now, I should be able to get ALL possible solutions. Am I able to do this with the backtracking algoritme and how? If not possible, which other (simple) algorithm should I use?


回答1:


This question is not a great fit for this site since it does not appear to be about actual code.

But I'll take a shot at it anyways.

Of course you can get all possible solutions with a backtracking algorithm. Remember how a backtracking algorithm works:

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.

If you want all solutions then just modify the algorithm to:

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.

Incidentally, I wrote a series of blog articles on solving sudoku in C# using a graph-colouring backtracking algorithm; it might be of interest to you:

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/graph-colouring-with-simple-backtracking-part-one

In this code you'll see the line:

return solutions.FirstOrDefault();

"solutions" contains a query that enumerates all solutions. I only want the first such solution, so that's what I ask it for. If you want every solution, just rewrite the program so that it does not call FirstOrDefault. See the comments below for some notes.



来源:https://stackoverflow.com/questions/15437568/how-to-get-all-possible-solutions-using-backtracking-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!