Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A cool algorithm to check a Sudoku field?

Does anyone know a simple algorithm to check if a Sudoku-Configuration is valid? The simplest algorithm I came up with is (for a board of size n) in Pseudocode

for each row
  for each number k in 1..n
    if k is not in the row (using another for-loop)
      return not-a-solution

..do the same for each column

But I'm quite sure there must be a better (in the sense of more elegant) solution. Efficiency is quite unimportant.

like image 363
user18670 Avatar asked Sep 10 '25 04:09

user18670


2 Answers

You need to check for all the constraints of Sudoku :

  • check the sum on each row
  • check the sum on each column
  • check for sum on each box
  • check for duplicate numbers on each row
  • check for duplicate numbers on each column
  • check for duplicate numbers on each box

that's 6 checks altogether.. using a brute force approach.

Some sort of mathematical optimization can be used if you know the size of the board (ie 3x3 or 9x9)

Edit: explanation for the sum constraint: Checking for the sum first (and stoping if the sum is not 45) is much faster (and simpler) than checking for duplicates. It provides an easy way of discarding a wrong solution.

like image 64
Radu094 Avatar answered Sep 13 '25 03:09

Radu094


Peter Norvig has a great article on solving sudoku puzzles (with python),

https://norvig.com/sudoku.html

Maybe it's too much for what you want to do, but it's a great read anyway

like image 39
daniel Avatar answered Sep 13 '25 02:09

daniel