36. Valid Sudoku
题意:
测试一个9*9的数独是否合法。
思路:
暴力求解,先测试每行,再测试每列,最后测试每块。遇到不合法直接返回false;
bool isValidSudoku(vector<vector<char>>& board) {
set<char> t({ '1','2','3','4','5','6','7','8','9' });
for (int i = 0; i < 9; ++i) {
set<char> a = t;
for (int j = 0; j < 9; ++j)
if (board[i][j] == '.')
continue;
else if (a.count(board[i][j]) == 0){
cout << "1";
return false;
}
else
a.erase(board[i][j]);
}
for (int i = 0; i < 9; ++i) {
set<char> a = t;
for (int j = 0; j < 9; ++j)
if (board[j][i] == '.')
continue;
else if (a.count(board[j][i]) == 0) {
cout << "2";
return false;
}
else
a.erase(board[j][i]);
}
for (int i = 0; i < 9; ++i) {
set<char> a = t;
for (int j = 0; j < 9; ++j)
if (board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] == '.')
continue;
else if (a.count(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]) == 0){
cout << "3";
return false;
}
else
a.erase(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]);
}
return true;
}