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.
分析:使用hash表记录,每一行上是否重复,每一列上是否重复,某一块九宫格是否重复。 为什么判断现有状况就一定能判断它是一个有效数独呢?
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
vector< vector<bool> > row(9, vector<bool>(9, false));
vector< vector<bool> > col(9, vector<bool>(9, false));
vector< vector<bool> > box(9, vector<bool>(9, false));
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
char ch = board[i][j];
if(ch == '.') continue;
ch -= '1';
if(row[i][ch] || col[j][ch] || box[i / 3 * 3 + j / 3][ch]) {
return false;
}
row[i][ch] = col[j][ch] = box[i / 3 * 3 + j / 3][ch] = true;
}
}
return true;
}
};