Sudoku solving algorithm C++

前端 未结 4 1737
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  甜味超标
    2021-01-31 07:25

    Suggested Approach

    1. Implement a generic graph search algorithm
      • could use either IDFS or A* graph search
        • I would prefer the second
      • do this for a general directed graph
        • node type TNode
        • node successor function TNode => vector
    2. Define your Sudoku states
      • a state is a 9x9 array with a number 1, 2, ..., or 9 or a blank in each position
    3. Define what a goal Sudoku state is
      • all 81 cells filled in
      • all 9 rows have numbers {1, 2, ..., 9} in them
      • all 9 columns have numbers {1, 2, ..., 9} in them
      • all 9 3x3 squares have numbers {1, 2, ..., 9} in them
    4. Define your valid Sudoku state successor function
      • a state S can have number N added at row I, column J if:
        • cell (I,J) is empty
        • there is no other N in row I
        • there is no other N in column J
        • there is no other N in the 3x3 square containing (I,J)
      • the state successor function maps a state S to the vector of states that satisfy these rules
    5. Apply your generic graph search algorithm (1) to the Sudoku state graph (2-4)
    6. (optional) If you do choose to use A* graph search, you can also define a heuristic on your Sudoku state space to potentially drastically increase performance
      • how to design the heuristic is another whole problem, that's more of an art than a science

    Current Approach

    Your current approach mixes the specification of the graph to be searched and the implementation of the search algorithm. You're going to have a lot of difficulty if you mix those two. This problem naturally separates into two distinct pieces -- the algorithm and the graph -- so you can and should exploit that in your implementation. It will make it much simpler.

    The other benefit you get if you go with this separation is that you will be able to reuse your graph search algorithm on a huge number of problems - very cool!

提交回复
热议问题