题目描述
The Sudoku board could be partially filled, where empty cells are filled with the character'.'.
A partially filled sudoku which is valid.
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
//记录已经出现的数,如3出现,则row[3]=1
int row[10] = {0};//之所以是10,因为下标最大是9
int col[9][10] = {0};
int square[9][10] = {0};
//行遍历,两层循环即可,只要找到重复的数即返回false
for(int i=0; i<9; i++){
//由于行重复使用了,所以每次都要清空
memset(row, 0, sizeof(row));
for(int j=0; j<9; j++){
if(board[i][j] != '.'){
if(!check(row, board[i][j] - '0') ||
!check(col[j], board[i][j] - '0') ||
//九宫格的序号:i/3*3 + j/3
!check(square[i/3*3 + j/3], board[i][j] - '0')
)
return false;
}
}
}
return true;
}
bool check(int a[], int v){
//如果每行或每列或每个九宫格出现了重复的数,那么返回false
if(a[v] == 1) return false;
a[v] = 1;
return true;
}
};