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.
方法:解此问题的关键是要在备选集合里挨个进行试,不是每个空格一开始只有一个唯一的固定数可以填的
class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
vector<set<char>> rowMap();
vector<set<char>> colMap();
vector<set<char>> boxMap();
vector<pair<int,int>> blank;
for(int i=;i<;i++)
{
for(int j=;j<;j++)
{
if(board[i][j]=='.')
{
blank.push_back(pair<int,int>(i,j));
continue;
}
rowMap[i].insert(board[i][j]);
}
}
for(int j=;j<;j++)
{
for(int i=;i<;i++)
{
if(board[i][j]=='.')
continue;
colMap[j].insert(board[i][j]);
}
}
for(int i=;i<;i=i+)
{
for(int j=;j<;j=j+)
{
vector<int> mp(,);
for(int k=;k<;k++)
{
for(int m=;m<;m++)
{
if(board[i+k][j+m]=='.')
continue;
boxMap[(i/) * +j/].insert(board[i+k][j+m]);
}
}
}
}
found = false;
DFS(,blank,rowMap,colMap,boxMap,board); }
private:
void DFS(int t, vector<pair<int,int>> &blank, vector<set<char>> &rowMap, vector<set<char>> &colMap, vector<set<char>> &boxMap, vector<vector<char> > &board)
{
if(t>=blank.size())
{
found = true;
}
else
{
int i= blank[t].first;
int j= blank[t].second;
for(char digit ='';digit<='';digit++)
{
if(rowMap[i].count(digit)> || colMap[j].count(digit)> || boxMap[i/ * + j/].count(digit)>)
{
continue;
}
board[i][j]=digit;
rowMap[i].insert(digit);
colMap[j].insert(digit);
boxMap[i/*+j/].insert(digit);
DFS(t+,blank,rowMap,colMap,boxMap,board);
rowMap[i].erase(digit);
colMap[j].erase(digit);
boxMap[i/*+j/].erase(digit);
if(found)
return;
}
}
}
private:
bool found; };