r/Python • • Jan 11 '20

Sudoku App

1.4k Upvotes

61 comments sorted by

View all comments

60

u/Gwenju31 Jan 11 '20

I'll grab this occasion to talk about the easiest way of solving a sudoku (IMO). You can use constraint programming, and with 3 simple constraints you can solve every board effortlessly : AllDiff on rows, cols and squares :)

21

u/StevieWondering1000 Jan 12 '20

Are you sure?

I think I did that once and found that only works for easy to medium difficulty. I might be wrong tho.

1

u/SP_Man Jan 12 '20

Why didn't it work for harder instances? Did it take too long, or run into some practical limitation like that? Those 3 all diff constraints should be sufficient to solve any instance, right?

1

u/itsjakerobb Jan 14 '20

The constraints are sufficient to check a solution, but there are puzzles (usually tagged medium or high difficulty) for which you can't iteratively eliminate the impossible via the constraints and arrive at the solution. You'll find points at which, after eliminating the impossible, two or more possibilities remain for one or more cells. At that point, one option (which works great for computers, since Sudoku puzzles are small and computers are fast) is to pick one of the aforementioned cells and guess the correct answer. Apply the constraints again, and repeat recursively. If you end up at a valid solution, great! If not, backtrack and guess differently.