C++解法1:暴力解法
class Solution {
public:
bool isValidSingle(vector<char>& matrix){
vector<int> flag = {0, 0, 0, 0, 0, 0, 0, 0, 0};
for(char m: matrix){
if(m != '.'){
flag[m-'0'-1]++;
}
}
for(int i: flag){
if(i>1) return false;
}
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
vector<char> temp(9, '.');
for(int i = 0; i<9; i++){
//col
for(int row=0; row<9;row++){
temp[row] = board[row][i];
}
if(!isValidSingle(temp)) return false;
//row
for(int col=0; col<9; col++){
temp[col] = board[i][col];
}
if(!isValidSingle(temp)) return false;
//3x3
if(i % 3 == 2){
for(int j = 0; j<9; j++){
if(j%3==2){
for(int x = 0; x<3; x++){
for(int y = 0; y<3; y++){
temp[3*x+y] = board[i-2+x][j-2+y];
}
}
if(!isValidSingle(temp)) return false;
}
}
}
}
return true;
}
};
C++解法2:哈希表数组
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][10] = {0};// 哈希表存储每一行的每个数是否出现过,默认初始情况下,每一行每一个数都没有出现过
// 整个board有9行,第二维的维数10是为了让下标有9,和数独中的数字9对应。
int col[9][10] = {0};// 存储每一列的每个数是否出现过,默认初始情况下,每一列的每一个数都没有出现过
int box[9][10] = {0};// 存储每一个box的每个数是否出现过,默认初始情况下,在每个box中,每个数都没有出现过。整个board有9个box。
for(int i=0; i<9; i++){
for(int j = 0; j<9; j++){
// 遍历到第i行第j列的那个数,我们要判断这个数在其所在的行有没有出现过,
// 同时判断这个数在其所在的列有没有出现过
// 同时判断这个数在其所在的box中有没有出现过
if(board[i][j] == '.') continue;
int curNumber = board[i][j]-'0';
if(row[i][curNumber]) return false;
if(col[j][curNumber]) return false;
if(box[j/3 + (i/3)*3][curNumber]) return false;
row[i][curNumber] = 1;// 之前都没出现过,现在出现了,就给它置为1,下次再遇见就能够直接返回false了。
col[j][curNumber] = 1;
box[j/3 + (i/3)*3][curNumber] = 1;
}
}
return true;
}
};
//作者:liujin-4
//链接:https://leetcode-cn.com/problems/valid-sudoku/solution/36-jiu-an-zhao-cong-zuo-wang-you-cong-shang-wang-x/