先看题:
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.
第一道逼我用vs调试的的题;心好累。。。
解这道题我首先维护一个9*9*9的矩阵,代表第i,j个位置可不可以放置k这个数字,初始化为0,代表可以放入,然后读入原始数独数据,开始维护这个矩阵,从(0,0)处开始递归了。
下面附上代码:
class Solution {
public:
vector<vector<char>> chess;
vector<vector<vector<char> > > che;//如果是0则可以填入,否则不可以填
bool solve(int m,int n){
bool flag=false;
if(chess[m][n]!='.'){//该位置已经有数字的时候
while(chess[m][n]!='.'){//跳过所有数字
if(n<8)n++;
else if(n==8&&m==8){
return true;
}
else{
n=0;
m++;
}
}
flag=solve(m,n);
return flag;
}
else{
for(int i=0;i<9&&!flag;++i){//从1开始试
if(!che[m][n][i]){//如果是0的话可以填入
int mm=m,nn=n; //用于记录当前位置
chess[m][n]=i+'1';
for(int k=0;k<9;++k)//填入一个数字后修改che矩阵,+1
che[m][k][i]+=1;
for(int k=0;k<9;++k)
che[k][n][i]+=1;
int mmm=m/3*3,nnn=n/3*3;
for(int k=0;k<3;++k){
for(int z=0;z<3;++z){
che[mmm+k][nnn+z][i]+=1;
}
}
if(nn<8){
nn++;
flag=solve(m,nn);
}
else if(n==8&&m==8){
return true;
}
else{
nn=0;
mm++;
flag=solve(mm,nn);
}
if(!flag){
chess[m][n]='.';//该数字不行的话修改che矩阵,-1
for(int k=0;k<9;++k)
che[m][k][i]-=1;
for(int k=0;k<9;++k)
che[k][n][i]-=1;
int mmm=m/3*3,nnn=n/3*3;
for(int k=0;k<3;++k){
for(int z=0;z<3;++z){
che[mmm+k][nnn+z][i]-=1;
}
}
}
else{
return true;
}
}
}
}
return false;
}
void solveSudoku(vector<vector<char>>& board) {
chess=board;
for(int i=0;i<9;++i){
vector<vector<char>> temp1;
for(int i=0;i<9;++i){
vector<char> temp(9,0);
temp1.push_back(temp);
}
che.push_back(temp1);
}
for(int i=0;i<9;++i){//读入原始数独数组
for(int j=0;j<9;++j){
if(chess[i][j]=='.')continue;
else{ //如果chess[i][j]是数字
for(int k=0;k<9;++k)
che[i][k][chess[i][j]-'1']+=1;//所在行每一个位置的che+1
for(int k=0;k<9;++k)
che[k][j][chess[i][j]-'1']+=1;//所在列每一个位置的che+1
int mmm=i/3*3,nnn=j/3*3;
for(int k=0;k<3;++k){
for(int z=0;z<3;++z){
che[mmm+k][nnn+z][chess[i][j]-'1']+=1;//所在小方框每一个位置的che+1
}
}
}
}
}
bool flag;
flag=solve(0,0);
board=chess;
}
};