A cool algorithm to check a Sudoku field?

前端 未结 25 754
清酒与你
清酒与你 2021-01-30 09:19

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

f         


        
25条回答
  •  不思量自难忘°
    2021-01-30 10:02

    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.

提交回复
热议问题