【Leetcode】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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool isValidSudoku(const vector<vector<char>>& board) { 4 bool used[9]; 5 for (int i = 0; i < 9; ++i) { 6 memset(used, false, 9); 7 for (int j = 0; j < 9; ++j) { 8 if (board[i][j] == '.') continue; 9 if (used[board[i][j] - '1']) { 10 return false; 11 } else { 12 used[board[i][j] - '1'] = true; 13 } 14 } 15 memset(used, false, 9); 16 for (int j = 0; j < 9; ++j) { 17 if (board[j][i] == '.') continue; 18 if (used[board[j][i] - '1']) { 19 return false; 20 } else { 21 used[board[j][i] - '1'] = true; 22 } 23 } 24 } 25 for (int r = 0; r < 3; ++r) { 26 for (int c = 0; c < 3; ++c) { 27 memset(used, false, 9); 28 for (int i = 0; i < 3; ++i) { 29 for (int j = 0; j < 3; ++j) { 30 int v1 = r * 3 + i; 31 int v2 = c * 3 + j; 32 if (board[v1][v2] == '.') continue; 33 if (used[board[v1][v2] - '1']) { 34 return false; 35 } else { 36 used[board[v1][v2] - '1'] = true; 37 } 38 } 39 } 40 } 41 } 42 return true; 43 } 44 };
依次检查即可,开始自作聪明想要在一个大的循环里面把三种方式都检查了,但是发现在检查小方块时下标运算会有除法和求模,反而使得程序变慢,另列一个3*3的循环虽然使代码变得复杂一点,但是思路清晰,且速度更快。