A cool algorithm to check a Sudoku field?

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

    Let's assume that your board goes from 1 - n.

    We'll create a verification array, fill it and then verify it.

    grid [0-(n-1)][0-(n-1)]; //this is the input grid
    //each verification takes n^2 bits, so three verifications gives us 3n^2
    boolean VArray (3*n*n) //make sure this is initialized to false
    
    
    for i = 0 to n
     for j = 0 to n
      /*
       each coordinate consists of three parts
       row/col/box start pos, index offset, val offset 
      */
    
      //to validate rows
      VArray( (0)     + (j*n)                             + (grid[i][j]-1) ) = 1
      //to validate cols
      VArray( (n*n)   + (i*n)                             + (grid[i][j]-1) ) = 1
      //to validate boxes
      VArray( (2*n*n) + (3*(floor (i/3)*n)+ floor(j/3)*n) + (grid[i][j]-1) ) = 1
     next    
    next
    
    if every array value is true then the solution is correct. 
    

    I think that will do the trick, although i'm sure i made a couple of stupid mistakes in there. I might even have missed the boat entirely.

提交回复
热议问题