[leetcode] 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.
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
1 class Solution 2 { 3 public: 4 bool isValidSudoku(vector<vector<char> > &board) 5 { 6 int i = 0, j = 0; 7 map<char, int> count; 8 9 //判断行是否合法 10 for(i = 0; i < 9; i++) 11 { 12 count.clear(); 13 for(j = 0; j < 9; j++) 14 { 15 count[board[i][j]]++; 16 if(count[board[i][j]] > 1 && board[i][j] != '.') 17 return false; 18 } 19 } 20 21 //判断列是否合法 22 for(i = 0; i < 9; i++) 23 { 24 count.clear(); 25 for(j = 0; j < 9; j++) 26 { 27 count[board[j][i]]++; 28 if(count[board[j][i]] > 1 && board[j][i] != '.') 29 return false; 30 } 31 } 32 33 // 判断九个小方块是否合法 34 for(i = 0; i < 9; i = i+3) 35 { 36 for(j = 0; j < 9; j = j+3) 37 { 38 count.clear(); 39 for(int m = 0; m < 3; m++) 40 { 41 for(int n = 0; n < 3; n++) 42 { 43 count[board[i + m][j + n]]++; 44 if(count[board[i + m][j + n]] > 1 && board[i + m][j + n] != '.') 45 return false; 46 } 47 } 48 } 49 } 50 51 return true; 52 } 53 };