A cool algorithm to check a Sudoku field?

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

    Some time ago, I wrote a sudoku checker that checks for duplicate number on each row, duplicate number on each column & duplicate number on each box. I would love it if someone could come up one with like a few lines of Linq code though.

    char VerifySudoku(char grid[81])
    {
        for (char r = 0; r < 9; ++r)
        {
            unsigned int bigFlags = 0;
    
            for (char c = 0; c < 9; ++c)
            {
                unsigned short buffer = r/3*3+c/3;
    
                            // check horizontally
                bitFlags |= 1 << (27-grid[(r<<3)+r+c]) 
                            // check vertically
                         |  1 << (18-grid[(c<<3)+c+r])
                            // check subgrids
                         |  1 << (9-grid[(buffer<<3)+buffer+r%3*3+c%3]);
    
            }
    
            if (bitFlags != 0x7ffffff)
                return 0; // invalid
        }
    
        return 1; // valid
    }
    

提交回复
热议问题