题目:
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.
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
if(board.size() != 9) return false;
bool rows[9][10] = {0};
bool cols[9][10] = {0};
bool subs[9][10] = {0};
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] == '.') continue;
int val = board[i][j] - '0';
if(rows[i][val] != 0 || cols[j][val] != 0 || subs[3*(i/3)+j/3][val] != 0) return false;
rows[i][val] = 1;
cols[j][val] = 1;
subs[3*(i/3)+j/3][val] = 1;
}
}
return true;
}
};
注意:1.子块位置的计算:i/3*3+j/3
2.键值是数组下标,是1-9这几个数字而不是1-9这几个字符,所以board[i][j]-'0'
3.因为需要的是1-9,行、列、子块各九个,所以每个哈希表的大小都是9*10(而不是9*9,这样就不存在[i][9]了)