//用BFS+康拓展开解决这道题目
#include <iostream>
#include<cstdio>
#include<string.h>
#include<queue>
using namespace std;
const int N=9;
const int MAXSIZE = 362880;
/*int N(int d)
{
if(i==0)
{
return 1;
}
else
{
int sum=1;
for(int i=1;i<=d;i++)
{
sum*=i;
}
return sum;
}
}
const MAXSiZE=N(8);
int fac[]={N(0),N(1),N(2),N(3),N(4),N(5),N(6),N(7),N(8)};
*/
int fac[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };//..
struct node
{
int map[9];
int dir;
};
int Order(const int *cur,int n)//康拓展开运算
{
int i,j,temp,num=0;
for(i=0;i<n;i++)
{
temp=0;
for(j=i+1;j<n;j++)
{
if(cur[i]>cur[j])
{
temp++;
}
}
num+=fac[n-i-1]*temp;
}
return (num);
}
int hash(const int *cur)
{
return Order(cur,9);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
void getNode(int num,node &tmp)//康拓展开逆运算
{
int a[9];
int i;
int n=9;
num=num;
for(i=n-1;i>=1;i--)
{
a[n-i-1]=num/fac[i];
num=num%fac[i];
tmp.map[i]=0;
}
tmp.map[0]=0;
a[n-1]=0;
int j;
int dir=0;
int flag[10]={0};
for(i=0;i<n;i++)
{
dir=0;
for(j=0;j<n;j++)
{
if(flag[j]==0)
{
dir++;
}
if(dir-1==a[i])
{
tmp.map[i]=j+1;
flag[j]=1;
break;
}
}
}
for(i=0;i<n;i++)
{
if(tmp.map[i]==9)
{
tmp.dir=i;
break;
}
}
}
int visit[MAXSIZE];//标记是否又走过
int parent[MAXSIZE];//路径
int move[MAXSIZE];//路径的移动
int dx[]={0,0,-1,1};//u d l r
int dy[]={-1,1,0,0};
void BFS(const node &start)//广搜
{
queue<int> que;
int i;
int u;
for(i=0;i<MAXSIZE;i++)
{
visit[i]=0;
}
u=hash(start.map);
visit[u]=1;
parent[u]=-1;
que.push(u);
node tem,cur;
int x,y,tp,v;
while(!que.empty())
{
u=que.front();
que.pop();
getNode(u,cur);
for(i=0;i<4;i++)
{
tem=cur;
x=tem.dir%3+dx[i];
y=tem.dir/3+dy[i];
if(x>=0&&x<=2&&y>=0&&y<=2)
{
y=y*3+x;
tp=tem.map[y];
tem.map[y]=tem.map[tem.dir];
tem.map[tem.dir]=tp;
tem.dir=y;
v=hash(tem.map);
if(visit[v]!=1)
{
move[v]=i;
visit[v]=1;
parent[v]=u;
if(v==0)
{
return ;
}
que.push(v);
}
}
}
}
}
void print(){//打印答案
int n, u;
int path[MAXSIZE];
n = 1;
path[0] = move[0];
u = parent[0];
while(parent[u] != -1){
path[n] = move[u];
++n;
u = parent[u];
}
for(int i=n-1; i>=0; --i){
if(path[i] == 0)
printf("u");
else if(path[i] == 1)
printf("d");
else if(path[i] == 2)
printf("l");
else
printf("r");
}
}
int main()
{
char d;
int i;
node start;
for(i=0;i<N;i++)
{
cin>>d;
if(d=='x')
{
start.map[i]=9;
start.dir=i;
}
else
{
start.map[i]=d-'0';
}
}
BFS(start);
if(visit[0] == 1)
print();
else
printf("unsolvable");
return 0;
}
poj 1077(康拓展开)
最新推荐文章于 2020-03-18 15:43:01 发布