A cool algorithm to check a Sudoku field?

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

    It would be very interesting to check if:

    when the sum of each row/column/box equals n*(n+1)/2
    and the product equals n!
    with n = number of rows or columns
    

    this suffices the rules of a sudoku. Because that would allow for an algorithm of O(n^2), summing and multiplying the correct cells.

    Looking at n = 9, the sums should be 45, the products 362880.

    You would do something like:

    for i = 0 to n-1 do
      boxsum[i] := 0;
      colsum[i] := 0;
      rowsum[i] := 0;
      boxprod[i] := 1;
      colprod[i] := 1;
      rowprod[i] := 1;    
    end;
    
    for i = 0 to n-1 do
      for j = 0 to n-1 do
        box := (i div n^1/2) + (j div n^1/2)*n^1/2;
        boxsum[box] := boxsum[box] + cell[i,j];
        boxprod[box] := boxprod[box] * cell[i,j];
        colsum[i] := colsum[i] + cell[i,j];
        colprod[i] := colprod[i] * cell[i,j];
        rowsum[j] := colsum[j] + cell[i,j];
        rowprod[j] := colprod[j] * cell[i,j];
       end;
    end;
    
    for i = 0 to n-1 do
      if boxsum[i] <> 45
      or colsum[i] <> 45
      or rowsum[i] <> 45
      or boxprod[i] <> 362880
      or colprod[i] <> 362880
      or rowprod[i] <> 362880
       return false;
    

提交回复
热议问题