POJ 3074 Sudoku (Dacing Links)

时间:2023-12-05 08:13:32

推荐一个写数独很好的博客:http://www.cnblogs.com/grenet/p/3163550.html

主要是把九宫格里的元素换到矩阵里面再求解dancing links

网上找的一模版

 #include<cstdio>
#include<cstring>
#define MAXM 10
#define MAXL 324
#define MAXN 240000
#define INF 0x7FFFFFFF
char sd[MAXM][MAXM];
int L[MAXN], R[MAXN], U[MAXN], D[MAXN], H[MAXN];
int size, C[MAXN], S[MAXN], X[MAXN], Q[MAXN], vis[MAXL * ];
bool Read()
{
int i, j;
for (i = ; i < MAXM; i++)
{
for (j = ; j < MAXM; j++)
{
scanf(" %c", &sd[i][j]);
if (sd[i][j] == 'e')
return false;
}
}
return true;
}
void Init()
{
int i;
for (i = ; i <= MAXL; i++)
{
L[i + ] = i;
R[i] = i + ;
U[i] = D[i] = i;
S[i] = ;
}
R[MAXL] = ;
size = MAXL + ;
}
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;
L[R[c]] = c;
R[L[c]] = c;
for (i = D[c]; i != c; i = D[i])
{
for (j = R[i]; j != i; j = R[j])
{
U[D[j]] = j;
D[U[j]] = j;
S[C[j]]++;
}
}
}
inline void Link(int r, int c)
{
D[size] = D[c];
U[size] = c;
U[D[c]] = size;
D[c] = size;
if (H[r] < )
H[r] = L[size] = R[size] = size;
else
{
L[size] = H[r];
R[size] = R[H[r]];
L[R[H[r]]] = size;
R[H[r]] = size;
}
S[c]++;
X[size] = r;
C[size++] = c;
}
bool Dance(int now)
{
int i, j, c, temp;
if (R[] == )
return true;
for (temp = INF,i = R[]; i; i = R[i])
{
if (S[i] < temp)
{
temp = S[i];
c = i;
}
}
Remove(c);
for (i = D[c]; i != c; i = D[i])
{
vis[X[i]] = true;
for (j = R[i]; j != i; j = R[j])
Remove(C[j]);
if (Dance(now + ))
return true;
for (j = L[i]; j != i; j = L[j])
Resume(C[j]);
vis[X[i]] = false;
}
Resume(c);
return false;
}
int main()
{
int i, j, k, r;
while (Read())
{
Init();
for (r = , i = ; i < MAXM; i++)
{
for (j = ; j < MAXM; j++)
{
if (sd[i][j] == '.')
{
for (k = ; k < MAXM; k++)
{
H[++r] = -;
Q[r] = k;
Link(r, (i - ) * + k);
Link(r, + (j - ) * + k);
Link(r, + ((i - ) / * + (j - ) / ) * + k);
Link(r, + (i - ) * + j);
}
}
else
{
H[++r] = -;
k = sd[i][j] - '';
Q[r] = k;
Link(r, (i - ) * + k);
Link(r, + (j - ) * + k);
Link(r, + ((i - ) / * + (j - ) / ) * + k);
Link(r, + (i - ) * + j);
}
}
}
memset(vis, false, sizeof(vis));
Dance();
for (i = ; i <= r; i++)
{
if (vis[i])
printf("%d", Q[i]);
}
putchar('\n');
}
return ;
}