class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
set<char> check;
typedef set<char>::iterator It;
typedef vector<char>::size_type sz;
sz len = board.size();
// check row
for (sz i = 0; i < len; ++i) {
for (sz j = 0; j < len; ++j) {
char ch = board[i][j];
if (ch != '.') {
It it = check.find(ch);
if (it != check.end())
return false;
else
check.insert(ch);
}
}
check.clear();
}
// check column
for (sz i = 0; i < len; ++i) {
for (sz j = 0; j < len; ++j) {
char ch = board[j][i];
if (ch != '.') {
It it = check.find(ch);
if (it != check.end())
return false;
else
check.insert(ch);
}
}
check.clear();
}
// check sub-boxes
for (sz i = 0; i < len; i += 3) {
for (sz j = 0; j < len; j += 3) {
for (sz m = 0; m < 3; ++m) {
for (sz n = 0; n < 3; ++n) {
char ch = board[i + m][j + n];
if (ch != '.') {
It it = check.find(ch);
if (it != check.end())
return false;
else
check.insert(ch);
}
}
}
check.clear();
}
}
return true;
}
};
参考后
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
typedef vector<char>::size_type sz;
sz len = board.size();
vector<int> vc(len, 0);
vector<vector<int> > checkR(len, vc);
vector<vector<int> > checkC(checkR);
vector<vector<int> > checkB(checkR);
// check row
for (sz i = 0; i < len; ++i) {
for (sz j = 0; j < len; ++j) {
char ch = board[i][j];
if (ch != '.') {
// check row
if (checkR[i][ch - '0' - 1] == 1 || checkC[j][ch - '0' - 1] == 1 || checkB[i / 3 * 3 + j / 3][ch - '0' - 1] == 1)
return false;
else {
// check row
checkR[i][ch - '0' - 1] = 1;
// check column
checkC[j][ch - '0' - 1] = 1;
// check sub-box
checkB[i / 3 * 3 + j / 3][ch - '0' - 1] = 1;
}
}
}
}
return true;
}
};