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.
1 vector<int> findLeastCandidate(vector<vector<char> > &board, vector<int> &out_digits){ 2 vector<int> idx; 3 int candidate_num = 10; 4 int n = board.size(); 5 for(int i = 0; i < n; i++){ 6 for(int j = 0; j < n; j ++) { 7 if(board[i][j] == '.'){ 8 static const int arr[] = {1,2,3,4,5,6,7,8,9}; 9 vector<int> digits(arr, arr + sizeof(arr) / sizeof(arr[0])); 10 //check row 11 for(int k = 0; k < n; k ++){ 12 if(board[i][k] != '.') 13 digits[board[i][k] - 48 - 1] = -1; 14 } 15 //check column 16 for(int k = 0; k < n; k ++){ 17 if(board[k][j] != '.') 18 digits[board[k][j] - 48 - 1] = -1; 19 } 20 //check the 9 sub-box 21 int row_box_idx = i/3; 22 int column_box_idx = j/3; 23 for(int l = row_box_idx * 3; l < (row_box_idx + 1) * 3; l ++){ 24 if(l == i) 25 continue; 26 for(int m = column_box_idx * 3; m < (column_box_idx + 1) * 3; m ++){ 27 if(board[l][m] != '.' && m != j) 28 digits[board[l][m] - 48 - 1] = -1; 29 } 30 } 31 //caculate candidate number 32 int tmp_num = 0; 33 for(int candidate: digits) 34 if(candidate != -1) 35 tmp_num ++; 36 37 if(tmp_num == 0){ 38 if(idx.size() == 0){ 39 idx.push_back(-1); 40 idx.push_back(-1); 41 }else { 42 idx[0] = -1; 43 idx[1] = -1; 44 } 45 return idx; 46 } 47 48 if(tmp_num < candidate_num){ 49 candidate_num = tmp_num; 50 out_digits = digits; 51 if(idx.size() == 0){ 52 idx.push_back(i); 53 idx.push_back(j); 54 }else { 55 idx[0] = i; 56 idx[1] = j; 57 } 58 } 59 } 60 } 61 } 62 return idx; 63 } 64 65 bool isValidSudoku(vector<vector<char> > &board) { 66 //find the candidate which has most constrict 67 vector<int> digits; 68 vector<int> idx = findLeastCandidate(board, digits); 69 if(idx.size() == 0) 70 return true; 71 72 if(idx[0] == -1) 73 return false; 74 75 int i = idx[0]; 76 int j = idx[1]; 77 //recursive 78 bool is_all_minus = true; 79 for(int candidate: digits) { 80 if(candidate != -1) { 81 is_all_minus = false; 82 board[i][j] = candidate + 48; 83 if(isValidSudoku(board)) 84 return true; 85 else 86 board[i][j] = '.'; 87 } 88 } 89 if(is_all_minus) 90 return false; 91 return false; 92 } 93 94 void solveSudoku(vector<vector<char> > &board) { 95 isValidSudoku(board); 96 }