首页 > 代码库 > Valid Sudoku

Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.‘.

 

A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

思路:检查每一行、每一列以及9个3*3的子块是否满足要求即可。

 1 class Solution { 2 public: 3     bool isValidSudoku( vector<vector<char> > &board ) { 4         short rowMark[9] = {0}, colMark[9] = {0}, squareMark[9] = {0}; 5         for( int i = 0; i < 9; ++i ) { 6             for( int j = 0; j < 9; ++j ) { 7                 if( board[i][j] == . ) { continue; } 8                 short bitflag = 1 << board[i][j]-1; 9                 if( ( rowMark[i] | colMark[j] | squareMark[i/3*3+j/3] ) & bitflag ) { return false; }10                 rowMark[i] |= bitflag;11                 colMark[j] |= bitflag;12                 squareMark[i/3*3+j/3] |= bitflag;13             }14         }15         return true;16     }17 };

 

Valid Sudoku