题目描述:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Input: [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] Output: true
代码:
class Solution {
public:
void initial(bool match[10][10]){
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= 9; j++){
match[i][j] = false;
}
}
}
bool isValidSudoku(vector<vector<char>>& board) {
bool row[10][10];
bool column[10][10];
bool box[10][10];
initial(row);
initial(column);
initial(box);
bool flag = 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] - '0';
if(row[i + 1][num]){
flag = true;
break;
}else row[i + 1][num] = true;
if(column[j + 1][num]){
flag = true;
break;
}else column[j + 1][num] = true;
int boxIndex = (i / 3) * 3 + j / 3 + 1;
if(box[boxIndex][num]){
flag = true;
break;
}else box[boxIndex][num] = true;
}
if(flag) break;
}
return !flag;
}
};
题目要求判断当前数独是否是正确的,一次AC,之所以给星标记是因为本题中二维数组作为形参的传入方式自己开始不正确。解题方法很简单,也很容易理解,如下:
首先初始化三个布尔类型的二维数组,row[10][10],column[10][10],box[10][10]。row[n][num]代表在数独盘中,第n行是否有num这个数,若有则为true,反之为false。column[n][num]代表在数独盘中,第n列是否有num这个数,若有则为true,反之为false。box数组也同理。然后只要遍历一下数独盘即可,当读取到数独盘中的一个数时,判断它是属于第几行,第几列,第几个box。并依次查看对应数组中的值是否为true,即是否存在这个值。若已经存在,则return false。
静心尽力!