Search code examples
c#solutionsudokubacktracking

How to get all possible solutions using backtracking algorithm?


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 algorithm and how? If not possible, which other (simple) algorithm should I use?


Solution

  • 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://learn.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.