A cool algorithm to check a Sudoku field?

前端 未结 25 1048
清酒与你
清酒与你 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 09:59

    You can check if sudoku is solved, in these two similar ways:

    • Check if the number is unique in each row, column and block.

    A naive solution would be to iterate trough every square and check if the number is unique in the row, column block that number occupies.

    But there is a better way.

    • Sudoku is solved if every row, column and block contains a permutation of the numbers (1 trough 9)

    This only requires to check every row, column and block, instead of doing that for every number. A simple implementation would be to have a bitfield of numbers 1 trough 9 and remove them when you iterate the columns, rows and blocks. If you try to remove a missing number or if the field isn't empty when you finish then sudoku isn't correctly solved.

提交回复
热议问题