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.
题意:给出一个数独,求解,保证有唯一解
分析:简单的思路是,遍历每个空格,枚举所有可能取值,递归求解。为了减小搜索空间,用启发式搜索。即,记录每个空格可能取值的种类,按从小到大遍历所有空格, 保证搜索空间最小。用三个set[9]分别记录每行,每列,每个3*3区域已有的数字,然后就能在O(1)内对相应的set做并集,求出任一空格可能的取值。
代码:
int cmp(const void *a, const void *b) { return ((int*)a)[2]-((int*)b)[2]; } class Solution { private: set<char> row[9],col[9],batch[9]; int op_qu[90][3],qu_cnt; public: bool fill(vector<vector<char> > &bd,int num) { if(num>=qu_cnt) return true; int i=op_qu[num][0],j=op_qu[num][1]; set<char> tmp,now; set_union(row[i].begin(),row[i].end(),col[j].begin(),col[j].end(),inserter(tmp,tmp.begin())); int k = i/3*3+j/3; set_union(tmp.begin(),tmp.end(),batch[k].begin(),batch[k].end(),inserter(now,now.begin())); for(char ch='1'; ch<='9'; ch++) { if(now.find(ch)==now.end()) { bd[i][j] = ch; row[i].insert(ch); col[j].insert(ch); batch[k].insert(ch); if(fill(bd,num+1)) return true; row[i].erase(ch); col[j].erase(ch); batch[k].erase(ch); } } return false; } void solveSudoku(vector<vector<char> > &board) { for(int i=0; i<9; i++) { row[i].clear(); col[i].clear(); batch[i].clear(); } qu_cnt = 0; for(int i=0; i<9; i++) { for(int j=0; j<9; j++) { char ch = board[i][j]; if(ch!='.') { row[i].insert(ch); col[j].insert(ch); batch[i/3*3+j/3].insert(ch); } } } for(int i=0; i<9; i++) { for(int j=0; j<9; j++) { char ch = board[i][j]; if(ch=='.') { set<char> tmp,now; set_union(row[i].begin(),row[i].end(),col[j].begin(),col[j].end(),inserter(tmp,tmp.begin())); int k = i/3*3+j/3; set_union(tmp.begin(),tmp.end(),batch[k].begin(),batch[k].end(),inserter(now,now.begin())); op_qu[qu_cnt][0] = i; op_qu[qu_cnt][1] = j; op_qu[qu_cnt][2] = 9-now.size(); qu_cnt++; } } } qsort(op_qu,qu_cnt,sizeof(int)*3,cmp); fill(board,0); } };