dfs,每次在?处尝试每个数字,若符合条件,则进行下一层dfs,知道找到足够的数字
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <queue>
#include <ctime>
#include <set>
#define ll long long
#define MK make_pair
#define PB push_back
#define SZ(x) ((int)(x).size())
#define FOR(it,c) for ( __typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++ )
using namespace std;
vector<int> vec;
bool avai[10][10][10],found;
int a[10][10];
bool ok(int x,int y,int n){
for(int i=0;i<9;i++) if(a[x][i]==n||a[i][y]==n) return false;
int nx=x/3*3,ny=y/3*3;
for(int i=nx;i<nx+3;i++) for(int j=ny;j<ny+3;j++) if(a[i][j]==n) return false;
return true;
}
void dfs(int d){
if(d==SZ(vec)){
found=true;
return;
}
if(found) return;
int x=vec[d]/9,y=vec[d]%9;
for(int i=1;i<=9;i++){
if(found) return;
if(!ok(x,y,i)) continue;
a[x][y]=i;
dfs(d+1);
if(found) return;
a[x][y]=0;
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
#endif
char s[100];
bool start=false;
while(~scanf("%s",s)){
if(start) cout<<endl;
start=true;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(s[0]=='?') a[i][j]=0;
else a[i][j]=s[0]-'0';
if(!(i==8&&j==8))
scanf("%s",s);
}
}
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(!a[i][j]) vec.PB(i*9+j);
found=false;
dfs(0);
for(int i=0;i<9;i++) for(int j=0;j<9;j++) cout<<a[i][j]<<(j==8?'\n':' ');
vec.clear();
}
return 0;
}