So, here’s the thing. I read someone else’s introductory article on Sudoku. I realized there were quite a few techniques… Ah, I didn’t want to think too much, so I decided to write a program to solve it instead. Why use brain power when a program can do at ease?
To solve it, you need a puzzle first
First of all, to write a solving program, you need a program to generate a Sudoku puzzle. (Actually, this is a special case of solving a puzzle where the grid is completely empty.)
The general algorithm is:
- Fill numbers into the Sudoku grid one by one.
- If there is no number that can be filled, backtrack to the previous position.
- Repeat this process until the entire grid is filled.
Sample code
|
|
Analysis
RestrictMatrix
First, RestrictMatrix is a hash table constraint matrix that records and updates the valid numbers that can be filled in each position of the grid in real-time according to Sudoku rules. According to the rules, it can save three hash tables of valid numbers corresponding to the position relationships:
- No repeated numbers in rows »> Save valid numbers by row, which is “rowMat”
- No repeated numbers in columns »> Save valid numbers by column, which is “colMat”
- No repeated numbers within the 3x3 subgrid »> Save valid numbers by subgrid index, which is “blockMat”
The actual numbers that can be placed in each position are the intersection of these three hash tables at that position (a series of numbers that are common to the three hash tables at that position). Each time a number is placed, it is taken out of the intersection of the corresponding positions of the three hash tables.
Using a hash table instead of a 0-1 matrix, a data structure commonly used in ordinary constraint programming, is mainly because its usage is simple and straightforward. (I’m not saying it’s because I rarely write programming problems, so I’m not very good at that method.)
__init__
Initialize the constraint matrix. Initially, since all positions are empty, any number can be filled. So, fill all with numbers 1-9.
|
|
drop
Called when a number v is placed in row r, column c. Update the valid numbers for the entire grid.
|
|
Here, discard is used to remove the number because we need to ignore the absence of the number.
put
Called when the number v is removed from row r, column c. Generally happens when there are no numbers to fill in the next candidate position and the current position needs to change the filled number. Since a different number needs to be filled, the number v that has been filled needs to be removed from the grid and put back into the constraint matrix. Also, the candidate numbers need to be updated.
|
|
validNums
Take the intersections of the three constraint hash tables for row r and column c to get the numbers that can be placed in the current position.
|
|
Solving steps
First, initialize the data structures to be used: the Sudoku grid, a constraint matrix, and a stack to record the current position and numbers tried (each time after trying, push the current state into the stack). If the position is filled with 0, it indicates that the position is empty and no number has been filled.
|
|
Start the solving loop. Using the stack size as a condition is just my habit; you’ll find out later that it actually never empties, and the loop will continue if there’s no exit condition.
|
|
At the beginning of each iteration, pop the current position and the numbers tried from the stack. At the first time, it will definitely be (0, 0) and {} (empty set). After continuous attempts and filling the next position, it will change.
|
|
Select the numbers that can be tried for the current position. These candidate numbers are obtained by removing the numbers already tried from the possible numbers for the current position.
|
|
If there are numbers that can be tried, proceed with filling.
|
|
Here, rand.choice is used to randomly select a number to fill.
If the current position is not 0, it means a number has been filled before, and it needs to be removed and put back into the constraint matrix.
|
|
After the checks, you can proceed with filling the number.
|
|
Also, record this number in the set of numbers tried. Push it back into the stack so it can be popped out and tried again when unable to proceed
|
|
After filling, check if it is complete. Since the filling order is from left to right and top to bottom, when the current position is (8, 8), it enters the last position. If the number can be filled, the entire grid is filled, and the Sudoku grid can be returned, exiting the loop.
|
|
If not, calculate the next position and push it into the stack to be tried next time.
|
|
If there are no numbers that can be tried at the current position, do not continue but remove the number (if any) that has been filled.
|
|
Finally, if a solution is obtained, print the Sudoku grid.
|
|
Rewriting into a general solving program
Since the program to generate the grid is essentially a special case of the solving program, it only needs to modify the candidate position update algorithm and the corresponding recording method to turn it into a general solving program.
Code
Only the gen_map function changes; the rest are exactly the same, so they are not listed one by one.
|
|
Analysis
First, compared to generating a grid where the numbers to be solved and the positions to be filled are known, general solving requires analyzing these first. Only positions filled with 0 need to be solved; others do not need to be touched or moved.
|
|
The update of the next position and the condition for determining if the solution is complete have also changed.
When the number of positions filled equals the number to be solved, it is complete.
The position update method is changed by taking a position to be solved from the end of the queue and placing it at the front, so that it can be taken out next time from the queue.
|
|
When there are no candidate numbers at the current position, a new position to be solved needs to be filled back into the queue but not at the front, because backtracking is needed.
|
|
Postscript
Actually, I know that my writing might have some readability issues and implementation considerations. If you have any comments or suggestions for improvement, feel free to message me privately. (Even so, it took me about a week to come up with this intermittently. I’m so bad…)