Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules (http://sudoku.com.au/TheRules.aspx).
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Solution: 1. Traverse the Sudoku only once.
2. Bit manipulation. Use only one bit to represent a number. Space: sizeof(int) * (1+9+9).
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char> > &board) { 4 const int N = 9; 5 int col[N] = {0}; 6 int box[N] = {0}; 7 8 for(int i = 0; i < N; i++) { 9 int row = 0; 10 for(int j = 0; j < N; j++) { 11 if(board[i][j] == '.') { 12 continue; 13 } 14 int bit = 1 << (board[i][j] - '1'); 15 int box_index = i/3*3 + j/3; 16 if((bit & row) || (bit & col[j]) || (bit & box[box_index])) { 17 return false; 18 } 19 row |= bit; 20 col[j] |= bit; 21 box[box_index] |= bit; 22 } 23 } 24 return true; 25 } 26 };