A cool algorithm to check a Sudoku field?

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

    Let's say int sudoku[0..8,0..8] is the sudoku field.

    bool CheckSudoku(int[,] sudoku)
    {
        int flag = 0;
    
    // Check rows
    for(int row = 0; row < 9; row++)
    {
        flag = 0;
        for (int col = 0; col < 9; col++)
        {
            // edited : check range step (see comments)
            if ((sudoku[row, col] < 1)||(sudoku[row, col] > 9)) 
            {
                return false;
            }
    
            // if n-th bit is set.. but you can use a bool array for readability
            if ((flag & (1 << sudoku[row, col])) != 0) 
            {
                return false;
            }
    
            // set the n-th bit
            flag |= (1 << sudoku[row, col]); 
        }
    }
    
    // Check columns
    for(int col= 0; col < 9; col++)
    {
        flag = 0;
        for (int row = 0; row < 9; row++)
        {
            if ((flag & (1 << sudoku[row, col])) != 0)
            {
                return false;
            }
            flag |= (1 << sudoku[row, col]);
        }
    }
    
    // Check 3x3 boxes
    for(int box= 0; box < 9; box++)
    {
        flag = 0;
        for (int ofs = 0; ofs < 9; ofs++)
        {
            int col = (box % 3) * 3;
            int row = ((int)(box / 3)) * 3;
    
            if ((flag & (1 << sudoku[row, col])) != 0)
            {
                return false;
            }
            flag |= (1 << sudoku[row, col]);
        }
    }
    return true;
    

    }

提交回复
热议问题