Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits
1-9
must occur exactly once in each row. - Each of the digits
1-9
must occur exactly once in each column. - Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
- The given board contain only digits
1-9
and the character'.'
. - You may assume that the given Sudoku puzzle will have a single unique solution.
- The given board size is always
9x9
.
题目的要求是根据规则填满九宫格,这道题一个比较简单的思路上使用递推,我们按从左到右,从上到下的顺序:
- 首先找到第一个空格
- 然后确定这个空格可能被填入的数字,填入这个数字后九宫格还能满足题目中的要求
- 找到第一个空格中可能被填入的数字后,在这些数字中依次选一个填进去,然后,寻找下一个空格,从这里进入递推
- 寻找下一个空格,然后在上一个空格已经被填入的情况下,确定本空格可能被填入的数字,如果本空格没有可填入的数字,则说明上一步填入的数字不对,返回第3步
- 直至所有空格都被填满,程序结束
递归的结束条件:
- 一是当空格中没有可填入的数字时,需返回
- 二是当填入当前所有可填入的数字都不能满足条件时,需将本空格重置为空,并返回
- 三是当所有的空格都被填满时
代码如下:
class Solution {
public:
bool solveSudoku(vector<vector<char>>& board) {
for( int i=0;i<9;i++ ){
for( int j=0;j<9;j++ ){
if( board[i][j] == '.' ){
vector<char> av = availableValue(i,j,board) ;
if( av.empty() ){
// cout<<"empty"<<endl ;
return false;
}
int size = av.size() ;
for( int k=0;k<size;k++ ){
board[i][j] = av[k] ;
// printRes(board) ;
bool res = solveSudoku(board) ;
// cout<<res<<endl ;
if( res ){
return true ;
}
else{
board[i][j] = '.' ;
}
}
if( board[i][j] == '.' ){
return false ;
}
}
}
}
return true ;
}
//find the available value of the specific cell
vector<char> availableValue(const int x,const int y,const vector<vector<char>>& board){
int a[10] = {0} ;
for( int i=0;i<9;i++ ){
if( board[x][i] != '.' ){
a[board[x][i]-'0'] = 1 ;
}
}
for( int i=0;i<9;i++ ){
if( board[i][y] !='.' ){
a[board[i][y]-'0'] = 1 ;
}
}
int x0 = 3*(x/3) ;
int y0 = 3*(y/3) ;
for( int i=x0;i<x0+3;i++ ){
for( int j=y0;j<y0+3;j++ ){
if( board[i][j] != '.' ){
a[board[i][j]-'0'] = 1 ;
}
}
}
vector<char> v ;
for( int i=1;i<10;i++ ){
if( a[i]==0 ){
v.push_back('0'+i) ;
}
}
return v ;
}
};