数独大家应该都很熟悉,所以理解题意对我们来说是很任意的,但刚开始看这道题的时候,还是被搞的头大,其实这道题的解题思路很容易理解,下面来具体讲述一下。
用两个二维数组储存横纵坐标并记录出现的次数,再用一个三维数组判断在一个3*3的方格内是否有重复的数字。用两个for循环遍历数组,以此来完成对数组的判断。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int rows[9][9];
int columns[9][9];
int subboxes [3][3][9];
memset(rows,0,sizeof(rows));
memset(columns,0,sizeof(columns));
memset(subboxes,0,sizeof(subboxes));
for(int i = 0;i < 9;i++){
for(int j = 0;j < 9;j++){
char c = board[i][j];
if(c != '.'){
int index = c - '0' - 1;//记录数字
rows[i][index]++; //
columns[j][index]++;
subboxes[i / 3][j / 3][index]++;
if(rows[i][index] > 1 || columns[j][index] > 1 || subboxes[i / 3][j / 3][index] > 1){//3*3 的格子中有重复数字
return false;
}
}
}
}
return true;
}
};