您的位置:首页 > 其它

Sudoku Solver [LeetCode]

2013-11-07 12:52 375 查看
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.



A sudoku puzzle...



...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 = 10;
int n = board.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j ++) {
if(board[i][j] == '.'){
static const int arr[] = {1,2,3,4,5,6,7,8,9};
vector<int> digits(arr, arr + sizeof(arr) / sizeof(arr[0]));
//check row
for(int k = 0; k < n; k ++){
if(board[i][k] != '.')
digits[board[i][k] - 48 - 1] = -1;
}
//check column
for(int k = 0; k < n; k ++){
if(board[k][j] != '.')
digits[board[k][j] - 48 - 1] = -1;
}
//check the 9 sub-box
int row_box_idx = i/3;
int column_box_idx = j/3;
for(int l = row_box_idx * 3; l < (row_box_idx + 1) * 3; l ++){
if(l == i)
continue;
for(int m = column_box_idx * 3; m < (column_box_idx + 1) * 3; m ++){
if(board[l][m] != '.' && m != j)
digits[board[l][m] - 48 - 1] = -1;
}
}
//caculate candidate number
int tmp_num = 0;
for(int candidate: digits)
if(candidate != -1)
tmp_num ++;

if(tmp_num == 0){
if(idx.size() == 0){
idx.push_back(-1);
idx.push_back(-1);
}else {
idx[0] = -1;
idx[1] = -1;
}
return idx;
}

if(tmp_num < candidate_num){
candidate_num = tmp_num;
out_digits = digits;
if(idx.size() == 0){
idx.push_back(i);
idx.push_back(j);
}else {
idx[0] = i;
idx[1] = 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() == 0)
return true;

if(idx[0] == -1)
return false;

int i = idx[0];
int j = idx[1];
//recursive
bool is_all_minus = true;
for(int candidate: digits) {
if(candidate != -1) {
is_all_minus = false;
board[i][j] = candidate + 48;
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: