Sudoku Solver [LeetCode]

时间:2022-04-01 20:50:10

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

Sudoku Solver [LeetCode]

A sudoku puzzle...

Sudoku Solver [LeetCode]

...and its solution numbers marked in red.

Summary: finds the cell which has the least candidates first, then checks all candidates in the cell.

    vector<int> findLeastCandidate(vector<vector<char> > &board, vector<int> &out_digits){
vector<int> idx;
int candidate_num = ;
int n = board.size();
for(int i = ; i < n; i++){
for(int j = ; j < n; j ++) {
if(board[i][j] == '.'){
static const int arr[] = {,,,,,,,,};
vector<int> digits(arr, arr + sizeof(arr) / sizeof(arr[]));
//check row
for(int k = ; k < n; k ++){
if(board[i][k] != '.')
digits[board[i][k] - - ] = -;
}
//check column
for(int k = ; k < n; k ++){
if(board[k][j] != '.')
digits[board[k][j] - - ] = -;
}
//check the 9 sub-box
int row_box_idx = i/;
int column_box_idx = j/;
for(int l = row_box_idx * ; l < (row_box_idx + ) * ; l ++){
if(l == i)
continue;
for(int m = column_box_idx * ; m < (column_box_idx + ) * ; m ++){
if(board[l][m] != '.' && m != j)
digits[board[l][m] - - ] = -;
}
}
//caculate candidate number
int tmp_num = ;
for(int candidate: digits)
if(candidate != -)
tmp_num ++; if(tmp_num == ){
if(idx.size() == ){
idx.push_back(-);
idx.push_back(-);
}else {
idx[] = -;
idx[] = -;
}
return idx;
} if(tmp_num < candidate_num){
candidate_num = tmp_num;
out_digits = digits;
if(idx.size() == ){
idx.push_back(i);
idx.push_back(j);
}else {
idx[] = i;
idx[] = j;
}
}
}
}
}
return idx;
} bool isValidSudoku(vector<vector<char> > &board) {
//find the candidate which has most constrict
vector<int> digits;
vector<int> idx = findLeastCandidate(board, digits);
if(idx.size() == )
return true; if(idx[] == -)
return false; int i = idx[];
int j = idx[];
//recursive
bool is_all_minus = true;
for(int candidate: digits) {
if(candidate != -) {
is_all_minus = false;
board[i][j] = candidate + ;
if(isValidSudoku(board))
return true;
else
board[i][j] = '.';
}
}
if(is_all_minus)
return false;
return false;
} void solveSudoku(vector<vector<char> > &board) {
isValidSudoku(board);
}