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.
class Solution { public: bool isValidSudoku(std::vector<std::vector<char> > &board) { int rows = board.size(); int cols = board[0].size(); int mask=0; int val; for(int i=0;i<rows;i++){ mask=0; for(int j=0;j<cols;j++){ if(board[i][j]!='.'){ int val = (int)(board[i][j]-'0'); if(mask & (1<<val)) return false; else mask |= (1<<val); } } } //rows are checked for(int j=0;j<cols;j++){ mask=0; for(int i=0;i<rows;i++){ if(board[i][j]!='.'){ int val = (int)(board[i][j]-'0'); if(mask & (1<<val)) return false; else mask |= (1<<val); } } } //cols are checked for(int i=0;i<rows;i+=3) { for(int j=0;j<cols;j+=3) { mask=0; for(int k=i;k<=i+2;k++) { for(int l=j;l<=j+2;l++) { if(board[k][l]!='.'){ val = (int)(board[k][l]-'0'); if(mask&(1<<val)) return false; else mask|=(1<<val); } } } } } return true; } };