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;
}
int size = board.size();
vector<vector<bool> > line(size, vector<bool>(size, false));
vector<vector<bool> > col(size, vector<bool>(size, false));
vector<vector<bool> > block(size, vector<bool>(size, false));
int i,j, blockId,res;
for (i=0; i<9; ++i) {
for (j=0; j<9; ++j) {
if (board[i][j] == '.') {
continue;
}
blockId = (i/3)*3+j/3;
res = board[i][j]-'1';
if (line[i][res] || col[j][res] || block[blockId][res]) {
return false;
}
line[i][res]=col[j][res]=block[blockId][res]=true;
}
}
return true;
}
};