描述
请编写一个程序,给数独中的剩余的空格填写上数字
空格用字符'.'表示
假设给定的数独只有唯一的解法
这盘数独的解法是:
红色表示填上的解
示例1
输入:
[[.,.,9,7,4,8,.,.,.],[7,.,.,.,.,.,.,.,.],[.,2,.,1,.,9,.,.,.],[.,.,7,.,.,.,2,4,.],[.,6,4,.,1,.,5,9,.],[.,9,8,.,.,.,3,.,.],[.,.,.,8,.,3,.,2,.],[.,.,.,.,.,.,.,.,6],[.,.,.,2,7,5,9,.,.]]
返回值:
[[5,1,9,7,4,8,6,3,2],[7,8,3,6,5,2,4,1,9],[4,2,6,1,3,9,8,7,5],[3,5,7,9,8,6,2,4,1],[2,6,4,3,1,7,5,9,8],[1,9,8,5,2,4,3,6,7],[9,7,5,8,6,3,1,2,4],[8,3,2,4,9,1,7,5,6],[6,4,1,2,7,5,9,8,3]]
//dfs
class Solution
{
public:
int a[88][2],cnt;
bool dfs(int p,vector<vector<char> > &board)
{
if(p==cnt)
return true;
int x=a[p][0],y=a[p][1];
int flag[11];
memset(flag,0,sizeof(flag));
for(int i=0;i<9;i++)
{
if(board[x][i]!='.')
flag[board[x][i]-'0']=1;
if(board[i][y]!='.')
flag[board[i][y]-'0']=1;
}
int xx=x/3,yy=y/3;
for(int i=3*xx;i<3*xx+3;i++)
for(int j=3*yy;j<3*yy+3;j++)
if(board[i][j]!='.')
{
flag[board[i][j]-'0']=1;
}
for(int i=1;i<=9;i++)
if(flag[i]==0)
{
board[x][y]='0'+i;
if(!dfs(p+1,board))
board[x][y]='.';
else
return true;
}
return false;
}
void solveSudoku(vector<vector<char> > &board)
{
int i,j;
cnt=0;
for(i=0;i<9;i++)
for(j=0;j<9;j++)
if(board[i][j]=='.')
{
a[cnt][0]=i;
a[cnt++][1]=j;
}
dfs(0,board);
}
};