链接:HDU - 1043
题意:九宫格还原
题解:康拓展开+BFS
#include <bits/stdc++.h>
using namespace std;
const int maxn = 9;
const int maxm = 370000;
struct Node{int a[maxn], num, n;};
struct Path{int fa; char dir;}Fa[maxm];
int f[maxn];
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
void set_fac()
{
f[0] = 1;
for(int i = 1; i < maxn; i++) f[i] = f[i-1] * i;
}
int Contor(int a[])
{
int ans = 0;
for(int i = 0; i < maxn; i++){
int k = 0;
for(int j = i + 1; j < maxn; j++){
if(a[i] > a[j]) k++;
}
ans += k * f[8 - i];
}
return ans;
}
void BFS(int a[])
{
Node p, q;
for(int i = 0; i < 9; i++) p.a[i] = a[i];
p.num = 0; p.n = 8;
queue<Node> Q;
Q.push(p);
Fa[p.num].fa = 0;
while(!Q.empty()){
p = Q.front(); Q.pop();
for(int i = 0; i < 4; i++){
int x = p.n / 3 + dx[i];
int y = p.n % 3 + dy[i];
if(x >= 0 && x < 3 && y >= 0 && y < 3){
q = p;
q.n = x * 3 + y;
swap(q.a[q.n], q.a[p.n]);
q.num = Contor(q.a);
if(Fa[q.num].fa == -1){
Fa[q.num].fa = p.num;
switch(i){
case 0 : Fa[q.num].dir = 'l'; break;
case 1 : Fa[q.num].dir = 'u'; break;
case 2 : Fa[q.num].dir = 'r'; break;
case 3 : Fa[q.num].dir = 'd'; break;
}
Q.push(q);
}
}
}
}
}
int main()
{
int a[maxn];
for(int i = 0; i < 9; i++) a[i] = i + 1;
for(int i = 0; i < maxm; i++) Fa[i].fa = -1;
set_fac();
BFS(a);
char s[maxn * 3];
while(gets(s) > 0){
for(int i = 0, k = 0; s[i]; i++){
if(s[i] == 'x') a[k++] = 9;
else if(s[i] >= '0' && s[i] <= '9') a[k++] = s[i] - '0';
}
int num = Contor(a);
if(Fa[num].fa == -1) puts("unsolvable");
else{
while(num != 0){
printf("%c", Fa[num].dir);
num = Fa[num].fa;
}
puts("");
}
}
return 0;
}