Sudoku solving algorithm C++

前端 未结 4 1686
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 07:04

I\'m trying to make a Sudoku Solving program for a couple of days but I\'m stuck with the methods. I found this algorithm here but I don\'t really understand it:

4条回答
  •  -上瘾入骨i
    2021-01-31 07:04

    The following assumes you are trying to solve a given board, not generate a puzzle.

    Basic (simple) approach

    Create a class whose objects can hold a board (here called board_t). This class may internally use array, but must support copying boards.

    Have a function void solve(board_t const& board); which repeats the following for each number n:

    • Copies your input
    • Enters n in the first empty cell of the copied board
    • If the copied board is a solution, print the solution and return.
    • Else If the board is still viable (e.g. no conflicts):
      • call solve(copied_board)

    Performance

    This is a recursive backtracking solution, which performs horribly for hard problems. You can significantly speed it up by proper pruning or deductive steps (e.g. if you end up with 8 numbers in a row after inserting one, you can immediately enter the ninth without any kind of search).

    Reasoning

    While certainly not an impressive technique, it has a high probability of working correctly, since you will only ever be modifying a copy to add a single value. This prevents corruption of your data structures (one problem your idea has is that it will destroy the numbers it finds when backtracking, are not necessarily the ones you just inserted, but may be part of the initial puzzle).

    Improving performance is quite simple, once you start picking more intelligent heuristics (e.g. instead of testing the square in order, you could pick the ones with the fewest remaining moves and try to get them out of the way - or do the reverse...) or start doing a bit of deduction and pruning.

    Note: The Algorithm Design Manual uses a Soduko solver to show the impact of these techniques on backtracking.

提交回复
热议问题