leetcode: Valid Sudoku
http://oj.leetcode.com/problems/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.
思路:
按行,按列,再按3 * 3小方块检查,只要都通过就返回true,不然就是false。
1 class Solution { 2 public: 3 bool isValidSudoku(vector<vector<char> > &board) { 4 int row, col, block; 5 char ch; 6 vector<int> marks(9, 0); 7 8 // Rows 9 for (row = 0; row < 9; ++row) { 10 marks.assign(9, 0); 11 12 for (col = 0; col < 9; ++col) { 13 ch = board[row][col]; 14 15 if (ch != '.') { 16 if (marks[ch - '1'] > 0) { 17 return false; 18 } 19 else { 20 ++marks[ch - '1']; 21 } 22 } 23 } 24 } 25 26 // Cols 27 for (col = 0; col < 9; ++col) { 28 marks.assign(9, 0); 29 30 for (row = 0; row < 9; ++row) { 31 ch = board[row][col]; 32 33 if (ch != '.') { 34 if (marks[ch - '1'] > 0) { 35 return false; 36 } 37 else { 38 ++marks[ch - '1']; 39 } 40 } 41 } 42 } 43 44 // Blocks 45 for (block = 0; block < 9; ++block) { 46 int start_row = (block / 3) * 3, start_col = (block % 3) * 3; 47 marks.assign(9, 0); 48 49 for (row = start_row; row < (start_row + 3); ++row) { 50 for (col = start_col; col < (start_col + 3); ++col) { 51 ch = board[row][col]; 52 53 if (ch != '.') { 54 if (marks[ch - '1'] > 0) { 55 return false; 56 } 57 else { 58 ++marks[ch - '1']; 59 } 60 } 61 } 62 } 63 } 64 65 return true; 66 } 67 };