Saturday, October 26, 2013

Solution to LeetCode Problems: 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.

Thoughts:
Mark every used number in a row, column or block. When a re-marking occurs, return false. Note the method used to calculate the block ID using row and column indices.

Solution:
  1. // ⑨ ばか
  2. #define BAKA 9  
  3.   
  4. class Solution {  
  5. public:  
  6.     bool isValidSudoku(vector<vector<char> > &board) {  
  7.         array<bool, BAKA> row[BAKA];  
  8.         array<bool, BAKA> col[BAKA];  
  9.         array<bool, BAKA> box[BAKA];  
  10.   
  11.         // as standard C array  
  12.         // the variables are not initialized...  
  13.         for(auto r = 0; r < BAKA; ++r)  
  14.             for(auto c = 0; c < BAKA; ++c)  
  15.                 row[r][c] = col[r][c] = box[r][c] = false;  
  16.   
  17.         for(auto r = 0; r < BAKA; ++r)  
  18.             for(auto c = 0; c < BAKA; ++c)  
  19.             {  
  20.                 char ch=board[r][c];  
  21.                 if (ch == '.')  
  22.                     continue;   // blank, no effect  
  23.                   
  24.                 ch -= '1';  
  25.                   
  26.                 if (row[r][ch])  
  27.                     return false;  
  28.                 row[r][ch] = true;  
  29.                   
  30.                 if (col[c][ch])  
  31.                     return false;  
  32.                 col[c][ch] = true;  
  33.                   
  34.                 if (box[r / 3 * 3 + c / 3][ch])  
  35.                     return false;  
  36.                 box[r / 3 * 3 + c / 3][ch] = true;  
  37.             }  
  38.               
  39.         return true;  
  40.     }  
  41. }; 

No comments:

Post a Comment