My first implementation:
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
set<char> rowHash;
for (int r=0; r<9; r++) {
rowHash.clear();
for (int c=0; c<9; c++) {
char cur = board[r][c];
if (cur != '.') {
pair<set<char>::iterator, bool> ret = rowHash.insert(cur);
if (!ret.second) {
return false;
}
}
}
}
set<char> columnHash;
for (int c=0; c<9; c++) {
columnHash.clear();
for (int r=0; r<9; r++) {
char cur = board[r][c];
if (cur != '.') {
pair<set<char>::iterator, bool> ret = columnHash.insert(cur);
if (!ret.second) {
return false;
}
}
}
}
set<char> subboxHash;
for (int box = 0; box<9; box++) {
int rowStart = (box/3)*3;
int columnStart = (box%3)*3;
subboxHash.clear();
for (int r = rowStart; r<rowStart+3; r++) {
for (int c = columnStart; c<columnStart+3; c++) {
char cur = board[r][c];
if (cur != '.') {
pair<set<char>::iterator, bool> ret = subboxHash.insert(cur);
if (!ret.second) {
return false;
}
}
}
}
}
return true;
}
};
my 2nd implementation
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
vector<bool> rowHash, columnHash;
// don't really need differentiate rows againt with columns
// but through the order of the reference
for (int i=0; i<9; i++) {
rowHash.assign(9, false);
columnHash.assign(9, false);
for (int j=0; j<9; j++) {
if (board[i][j] != '.') {
// Ascii value of '1' is 49, 'A' is 65, 'a' is 96
if (rowHash[board[i][j]-49]) {
return false;
}
rowHash[board[i][j]-49] = true;
}
if (board[j][i] != '.') {
if (columnHash[board[j][i]-49]) {
return false;
}
columnHash[board[j][i]-49] = true;
}
}
}
for (int i=0; i<9; i+=3) { //start of rows for each subbox
for (int j=0; j<9; j+=3) { //start of columns for each subbox
rowHash.assign(9, false);
for (int m=0; m<3; m++) { // row residual of each subbox
for (int n=0; n<3; n++) { // column residual of each subbox
if (board[i+m][j+n] != '.') {
if (rowHash[board[i+m][j+n]-49]) {
return false;
}
rowHash[board[i+m][j+n]-49] = true;
}
}
}
}
}
return true;
}
};