A cool algorithm to check a Sudoku field?

前端 未结 25 1149
清酒与你
清酒与你 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:08

    Check each row, column and box such that it contains the numbers 1-9 each, with no duplicates. Most answers here already discuss this.

    But how to do that efficiently? Answer: Use a loop like

    result=0;
    for each entry:
      result |= 1<<(value-1)
    return (result==511);
    

    Each number will set one bit of the result. If all 9 numbers are unique, the lowest 9 bits will be set. So the "check for duplicates" test is just a check that all 9 bits are set, which is the same as testing result==511. You need to do 27 of these checks.. one for each row, column, and box.

提交回复
热议问题