POJ 3074 Sudoku

POJ_3074

    为了练一下自己对Dancing Links的熟悉程度,做了一下这个题目。

#include<stdio.h>
#include<string.h>
#define INF 1000000000
const int N = 9;
const int mn = N * N * N * 4 + N * N * 4 + N;
const int nn = N * N * 4 + N;
int U[mn], D[mn], L[mn], R[mn], H[mn], C[mn], X[mn];
int S[nn], Q[nn], visc[nn], size;
char b[nn];
int a[nn][nn], ans[nn][nn];
void prepare(int r, int c)
{
int i;
for(i = 0; i <= c; i ++)
{
S[i] = 0;
U[i] = D[i] = i;
L[i + 1] = i;
R[i] = i + 1;
}
R[c] = 0;
size = c;
while(r)
H[r --] = -1;
}
void place(int &r, int &c1, int &c2, int &c3, int &c4, int i, int j, int k)
{
r = (i * N + j) * N + k;
c1 = i * N + j + 1;
c2 = N * N + i * N + k;
c3 = N * N * 2 + j * N + k;
c4 = N * N * 3 + (i / 3 * 3 + j / 3) * N + k;
}
void link(int r , int c)
{
size ++;
C[size] = c;
S[c] ++;
X[size] = r;
D[size] = D[c];
U[D[c]] = size;
U[size] = c;
D[c] = size;
if(H[r] < 0)
H[r] = L[size] = R[size] = size;
else
{
R[size] = R[H[r]];
L[R[H[r]]] = size;
L[size] = H[r];
R[H[r]] = size;
}
}
int init()
{
int i, j, k, r, c1, c2, c3, c4;
scanf("%s", b);
if(strcmp(b, "end") == 0)
return 0;
k = 0;
memset(visc, 0, sizeof(visc));
prepare(mn, N * N * 4);
for(i = 0; i < N; i ++)
for(j = 0; j < N; j ++)
{
if(b[k] != '.')
{
a[i][j] = b[k] - '0';
place(r, c1, c2, c3, c4, i, j, a[i][j]);
link(r, c1), link(r, c2), link(r, c3), link(r, c4);
visc[c2] = visc[c3] = visc[c4] = 1;
}
else
a[i][j] = 0;
k ++;
}
for(i = 0; i < N; i ++)
for(j = 0; j < N; j ++)
if(!a[i][j])
for(k = 1; k <= N; k ++)
{
place(r, c1, c2, c3, c4, i, j, k);
if(visc[c2] || visc[c3] || visc[c4])
continue;
link(r, c1), link(r, c2), link(r, c3), link(r, c4);
}
return 1;
}
void remove(int c)
{
int i, j;
L[R[c]] = L[c];
R[L[c]] = R[c];
for(i = D[c]; i != c; i = D[i])
for(j = R[i]; j != i; j = R[j])
{
U[D[j]] = U[j];
D[U[j]] = D[j];
S[C[j]] --;
}
}
void resume(int c)
{
int i, j;
for(i = U[c]; i != c; i = U[i])
for(j = L[i]; j != i; j = L[j])
{
S[C[j]] ++;
U[D[j]] = j;
D[U[j]] = j;
}
L[R[c]] = c;
R[L[c]] = c;
}
int dance(int cur)
{
int i, j, c, temp;
if(!R[0])
{
for(i = 0; i < cur; i ++)
{
int x = (X[Q[i]] - 1) / N / N;
int y = (X[Q[i]] - 1) / N % N;
ans[x][y] = (X[Q[i]] - 1) % N + 1;
}
return 1;
}
temp = INF;
for(i = R[0]; i != 0; i = R[i])
if(S[i] < temp)
{
temp = S[i];
c = i;
}
remove(c);
for(i = D[c]; i != c; i = D[i])
{
Q[cur] = i;
for(j = R[i]; j != i; j = R[j])
remove(C[j]);
if(dance(cur + 1))
return 1;
for(j = L[i]; j != i; j = L[j])
resume(C[j]);
}
resume(c);
return 0;
}
void printresult()
{
int i, j;
for(i = 0; i < N; i ++)
for(j = 0; j < N; j ++)
printf("%d", ans[i][j]);
printf("\n");
}
int main()
{
while(init())
{
dance(0);
printresult();
}
return 0;
}


你可能感兴趣的:(sudo)