public:
//可把三个限制条件放到一个循环里面处理
void solveSudoku(vector<vector<char> >& board) {
if(board.size()<=0 && board[0].size()<=0){
return;
}
int rowLimits[board.size()][9];
int colLimits[board[0].size()][9];
int blockLimits[(board.size()/3) * (board[0].size()/3)][9];
map<int,vector<int> > blankLimits;
vector<int> blank;
vector<int> digitLimits;
int limits[9] = {1,1,1,1,1,1,1,1,1};
//构造行限制
for (int i = 0; i < board.size(); i++)
{
digitLimits = vector<int>(limits,limits+9);
for (size_t j = 0; j < board[i].size(); j++)
{
if(board[i][j]!='.'){
digitLimits[board[i][j]-'1'] = 0;
}else{
blank.push_back(i*9+j);
}
}
for (size_t k = 0; k < digitLimits.size(); k++)
{
if(digitLimits[k]==1){
rowLimits[i][k]=1;
}else{
rowLimits[i][k]=0;
}
}
}
//构造列限制
for (int i = 0; i < board[0].size(); i++)
{
digitLimits = vector<int>(limits,limits+9);
for (size_t j = 0; j < board.size(); j++)
{
if(board[j][i]!='.'){
digitLimits[board[j][i]-'1'] = 0;
}
}
for (size_t k = 0; k < digitLimits.size(); k++)
{
if(digitLimits[k]==1){
colLimits[i][k]=1;
}else{
colLimits[i][k]=0;
}
}
}
//构造块限制
for (int i = 0; i < board.size(); )
{
if(i%3==0){
for (int j = 0; j < board[i].size(); )
{
if(j%3==0){
digitLimits = vector<int>(limits,limits+9);
for (int k = 0; k <= 2; k++)
{
for (int l = 0; l <= 2; l++)
{
if(board[i+k][j+l]!='.'){
digitLimits[board[i+k][j+l]-'1'] = 0;
}
}
}
for (int k = 0; k < digitLimits.size(); k++)
{
if(digitLimits[k]==1){
blockLimits[i/3 * 3+j/3][k] = 1;
}else{
blockLimits[i/3 * 3+j/3][k] = 0;
}
}
}
j+=3;
}
}
i+=3;
}
solveSudokuWithlimits(board,rowLimits,colLimits,blockLimits,blank,0);
return ;
}
bool solveSudokuWithlimits(vector<vector<char> >& board,int (*rowLimits)[9],int (*colLimits)[9],int (*blockLimits)[9],vector<int> &blank,int pos){
if(pos>=blank.size()){
return true;
}
//待填充坐标 (i,j)
//限制,rowLimits[blank[i][j]],colLimits[i],blockLimits[i/3 * 3+blank[i][j]/3];
int coordinate = blank[pos];
int i=coordinate/9;//row
int j=coordinate%9;//col
for (int k = 0; k < 9; k++)
{
if(rowLimits[i][k]==1
&&colLimits[j][k] == 1
&&blockLimits[i/3 * 3+j/3][k]==1
){
board[i][j] = k+'1';
rowLimits[i][k]=0;
colLimits[j][k]=0;
blockLimits[i/3 * 3+j/3][k]=0;
if(solveSudokuWithlimits(board,rowLimits,colLimits,blockLimits,blank,pos+1)){
return true;
}
board[i][j] = '.';
rowLimits[i][k]=1;
colLimits[j][k]=1;
blockLimits[i/3 * 3+j/3][k]=1;
}
}
return false;
}