1刷
0技术含量,复制了别人的代码,用map也是很容易的
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for(int i = 0; i < 9; i ++)
{
unordered_map<char, bool> m1; //check i_th row
unordered_map<char, bool> m2; //check i_th column
unordered_map<char, bool> m3; //check i_th subgrid
for(int j = 0; j < 9; j ++)
{
if(board[i][j] != '.')
{
if(m1[board[i][j]] == true)
return false;
m1[board[i][j]] = true;
}
if(board[j][i] != '.')
{
if(m2[board[j][i]] == true)
return false;
m2[board[j][i]] = true;
}
if(board[i/3*3+j/3][i%3*3+j%3] != '.')
{
if(m3[board[i/3*3+j/3][i%3*3+j%3]] == true)
return false;
m3[board[i/3*3+j/3][i%3*3+j%3]] = true;
}
}
}
return true;
}
};
2刷
不用3刷了,简单判断题,只是配合37题一起的
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_map<int, int>ma1;
unordered_map<int, int>ma2;
unordered_map<int, int>ma3;
for(int i = 0; i < 9; ++ i){
ma1.clear();
ma2.clear();
ma3.clear();
for(int j = 0; j < 9; ++ j){
if(board[i][j] != '.'){
ma1[board[i][j]]++;
if(ma1[board[i][j]] >= 2) return false;
}
if(board[j][i] != '.'){
ma2[board[j][i]]++;
if(ma2[board[j][i]] >= 2) return false;
}
if(board[(i / 3) * 3 + j / 3][(i % 3) * 3 + j % 3] != '.'){
ma3[board[(i / 3) * 3 + j / 3][(i % 3) * 3 + j % 3]]++;
if(ma3[board[(i / 3) * 3 + j / 3][(i % 3) * 3 + j % 3]] >= 2) return false;
}
}
}
return true;
}
};