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.
这是一道用到hash map的题目。
拿到这道题一上来的思路就是遍历所有元素,将每个元素都和同行、同列、同九宫格的元素比较,然后发现有很多重复操作。
然后想到可以用hash map(思路来源于Single Number II),将每行、每列、每九宫格出现的元素全部作为key存放在一个map中,如果当前行、列、方九宫格再次出现同一元素,则证明数独非法。
第一遍ac的代码(遍历三遍数组,分别确定行、列、九宫格是否合法)
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
int n = board.size();
if(!rowValid(board, n)) return false;
if(!colValid(board, n)) return false;
if(!blockValid(board,n)) return false;
return true;
}
bool rowValid(vector<vector<char> > board,int n){
map<char, int> m;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (board[i][j] == '.') continue;
if (m.find(board[i][j]) == m.end())
m[board[i][j]] = 1;
else return false;
}
m.clear();
}
return true;
}
bool colValid(vector<vector<char> > board, int n){
map<char, int> m;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (board[j][i] == '.') continue;
if (m.find(board[j][i]) == m.end())
m[board[j][i]] = 1;
else return false;
}
m.clear();
}
return true;
}
bool blockValid(vector<vector<char> > board, int n){
int m = n / 3;
map<char, int> mp;
for (int i = 0; i < m; i++){
for (int j = 0; j < m; j++){
for (int p = 0; p < 3; p++){
for (int q = 0; q < 3; q++){
if (board[i*3+p][j*3+q] == '.') continue;
if (mp.find(board[i*3+p][j*3+q]) == mp.end()){
mp[board[i * 3 + p][j * 3 + q]] = 1;
}
else return false;
}
}
mp.clear();
}
}
return true;
}
};
isValidSudoku里边本来写的 return rowValid(board,n)&&col
Valid(board,n)&&blockValid(board,n),后来发现这样写可能拉高了平均复杂度,最后还是分开写了。
第二遍ac的代码(只遍历一遍数组,用三个二维数组分别存放行、列、九宫格中元素出现的情况):
class Solution{
public:
bool isValidSudoku(vector<vector<char> > &board){
vector<vector<bool> > rows(9, vector<bool>(9, false));
vector<vector<bool> > cols(9, vector<bool>(9, false));
vector<vector<bool> > blocks(9, vector<bool>(9, false));
for (int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
if (board[i][j] == '.') continue;
int num = board[i][j] - '1';
if (rows[i][num] || cols[j][num] || blocks[i - i % 3 + j / 3][num])
return false;
rows[i][num] = cols[j][num] = blocks[i - i % 3 + j / 3][num] = true;
}
}
return true;
}
};
这段代码比较简洁一点,九宫格的坐标换算可能比较难想。前后两个方法的效率差距还挺大的。第一个120ms AC,第二个96ms AC。个人感觉是不是map的find方法浪费了时间?