题目描述
请编写一个程序,给数独中的剩余的空格填写上数字
空格用字符'.'表示
假设给定的数独只有唯一的解法
这盘数独的解法是:
红色表示填上的解
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<vector<
int
>> used1(9,vector<
int
>(9,0)),used2(9,vector<
int
>(9,0)),used3(9,vector<
int
>(9,0));
fillnum(used1,used2,used3,board);
solve(used1,used2,used3,board);
}
void
fillnum(vector<vector<
int
>> &used1,vector<vector<
int
>> &used2,vector<vector<
int
>> &used3,vector<vector<
char
> > &board) {
for
(
int
i=0;i<board.size();i++)
for
(
int
j=0;j<board[0].size();j++)
if
(board[i][j]!=
'.'
)
{
int
num=board[i][j]-
'0'
-1;
int
k=i/3*3+j/3;
used1[i][num]=used2[j][num]=used3[k][num]=1;
}
}
bool
solve(vector<vector<
int
>> &used1,vector<vector<
int
>> &used2,vector<vector<
int
>> &used3,vector<vector<
char
>>&board){
for
(
int
i=0;i<board.size();i++)
for
(
int
j=0;j<board[0].size();j++){
int
k=i/3*3+j/3;
if
(board[i][j]==
'.'
){
for
(
int
fill=1;fill<10;fill++){
if
(used1[i][fill-1]==0 && used2[j][fill-1]==0 && used3[k][fill-1]==0){
board[i][j]=fill+
'0'
;
used1[i][fill-1]=used2[j][fill-1]=used3[k][fill-1]=1;
if
(solve(used1,used2,used3,board))
return
true
;
board[i][j]=
'.'
;
used1[i][fill-1]=used2[j][fill-1]=used3[k][fill-1]=0;
}
}
return
false
;
}
}
return
true
;
}
};