Complex Sudoku ratio DFS fast//Space change time #include <stdio.h> #include <string.h> #include <iostream> using namespace std;
#define N 300000 #define INF 0x3fffffff Char g[10][10];
int ans[1000];
int u[5000],d[5000],r[5000],l[5000],num[5000],h[1000],save[5000],save1[5000];
int flag,head;
const int n=729;
const int m=324;
int id;
void Prepare () {for (int i=0;i<=m;i++) {num[i]=0;
D[i]=i;
U[i]=i;
r[i]=i+1;
L[i+1]=i;
} r[m]=0; memset (h,-1,sizeof (H));
Record the first point in each row} void link (int tn,int tm) {id++; Save1[id]=tn; Record line ++NUM[SAVE[ID]=TM];
Record column D[ID]=D[TM];
u[D[tm]]=id;
U[id]=tm;
D[tm]=id;
if (h[tn]<0) H[tn]=l[id]=r[id]=id;
else {r[id]=r[h[tn]];
l[R[h[tn]]]=id;
r[H[tn]]=id;
L[ID]=H[TN];
} void Build () {id=m;
int sum;
Prepare ();
int tn=0;
for (int i=1;i<=81;i++) {for (int j=1;j<=9;j++) { ++tn;
Link (tn,i);
}} sum=81;
for (int i=1;i<=9;i++)//each row {tn= (i-1) *81;
for (int k=1;k<=9;k++) {int tk=tn+k;
for (int j=1;j<=9;j++) {link (tk,sum+ (i-1) *9+k);
tk+=9;
}} sum+=81;
for (int i=1;i<=9;i++) {tn= (i-1) *9;
for (int k=1;k<=9;k++) {int tk=tn+k;
for (int j=1;j<=9;j++) {link (tk,sum+ (i-1) *9+k);
tk+=81;
}} sum+=81;
int tt=0;
for (int i1=1;i1<=3;i1++) {for (int j1=1;j1<=3;j1++) {tn= (i1-1) *81*3+9*3* (j1-1);
for (int k=1;k<=9;k++) {++tt;
int tk;
for (int i=1;i<=3;i++) {for (int j=1;j<=3;j++) {tk=tn+ (i-1) *81+9* (j-1) +k;
Link (TK,SUM+TT);
}}}} void remove (int s) {l[r[s]]=l[s];
r[L[s]]=r[s];
for (int i=d[s];i!=s;i=d[i]) (int j=r[i];j!=i;j=r[j]) {u[d[j]]=u[j];
D[U[J]]=D[J];
num[save[j]]--;
} void Resume (int s) {r[l[s]]=s;
L[r[s]]=s;
for (int i=u[s];i!=s;i=u[i]) (int j=l[i];j!=i;j=l[j]) {u[d[j]]=j;
D[u[j]]=j;
num[save[j]]++;
} void Dfs (int s) {if (flag) return;
if (r[head]==head) {flag=1;
for (int i=0;i<s;i++) {int ti,tj,tk;
int tans=save1[ans[i]]-1;
Ti= (tans)/81+1;
tj= (tans%81)/9+1;;
tk= (tans%81)%9+1; printf ("<%d%d> ", TI,TJ);
g[ti][tj]=tk+ ' 0 ';
} return;
int mi=inf,tu;
for (int i=r[head];i!=head;i=r[i]) if (Mi>num[i]) {mi=num[i];
Tu=i;
Remove (TU);
for (int i=d[tu];i!=tu;i=d[i]) {for (int j=r[i];j!=i;j=r[j]) remove (save[j]);
Ans[s]=i;
DFS (S+1);
for (int j=l[i];j!=i;j=l[j]) resume (save[j]);
} resume (TU);
int main () {int T;
scanf ("%d", &t);
while (t--) {build ();
int tu=0;
for (int i=1;i<=9;i++) {for (int j=1;j<=9;j++) {cin>>g[i][j];
if (g[i][j]!= ' 0 ') {int kk=g[i][j]-' 0 ';
Remove (save[H[TU+KK]]);
for (int i1=r[H[TU+KK]];i1!= h[tu+kk];i1=r[i1]) {remove (SAVE[I1));
} } tu+=9;
}} flag=0;
DFS (0);
printf ("\ n");
for (int i=1;i<=9;i++) {for (int j=1;j<=9;j++) printf ("%c", G[i][j]);
printf ("\ n");
} return 0;
}