1.八数码C++源代码
八数码C++源代码
#include<cstdio>
#include<vector>
#include<queue>
#include<ctime>
#define maxhash
#define hash(x) x%maxhash
using namespace std;
typedef unsigned long long ULL;
vector<ULL>list[maxhash];
vector<int>dist[maxhash];
inline int abs(int x)
{
return x<0?-x:x;
}
int hval[][];
void fill_hval(int *d)
{
for(int i=0;i<=8;i++)//number i
{
int pos;
for(int k=1;k<=9;k++)//i's position
if(d[k]==i)
{
pos=k;
break;
}
for(int j=1;j<=9;j++)
{
hval[i][j]=abs((j-1)/3-(pos-1)/3)+abs((j-1)%3-(pos-1)%3);
}
}
}
int h(ULL d)
{
int answer=0;
for(int i=9;i>=1;i--)
{
int x=d%;
d/=;
answer+=hval[x][i];
}
return answer;
}
int ToARR(ULL s,int *d)
{
int z=0;
for(int i=9;i>=1;i--)
{
d[i]=s%;
if(d[i]==0) z=i;
s/=;
}
return z;
}
ULL ToULL(int *d)
{
ULL ans=0;
for(int i=1;i<=9;i++)
ans=ans*+d[i];
return ans;
}
void insert(ULL x,int di)
{
ULL hx=hash(x);
list[hx].push_back(x);
dist[hx].push_back(di);
}
int find(ULL x)
{
ULL hx=hash(x);
int size=list[hx].size();
for(int i=0;i<size;i++)
if(x==list[hx][i]) return dist[hx][i];
return -1;
}
inline void swap(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
struct state{
int step;
ULL x;
friend bool operator <(state a,state b)
{
return a.step>b.step;
}
};
int cnt=0;
void AStar(int *from,int *to)
{
priority_queue<state>q;
ULL x=ToULL(from);
ULL y=ToULL(to);
fill_hval(to);
q.push((state){ h(x),x});
insert(x,0);
int d[];
while(!q.empty())
{
cnt++;
state s=q.top();
ULL i=s.x; q.pop();
int step=find(i);
int z=ToARR(i,d);
//printf("%lld %d %d\n",i,step,z);
if(i==y) return;
if(z-3>0)
{
swap(d[z],d[z-3]);
ULL j=ToULL(d);
swap(d[z],d[z-3]);
if(find(j)!=-1) goto out1;
q.push((state){ step+h(j),j});
insert(j,step+1);
}
out1:
if(z+3<)
{
swap(d[z],d[z+3]);
ULL j=ToULL(d);
swap(d[z],d[z+3]);
if(find(j)!=-1) goto out2;
q.push((state){ step+h(j),j});
insert(j,step+1);
}
out2:
if(z%3!=0)
{
swap(d[z],d[z+1]);
ULL j=ToULL(d);
swap(d[z],d[z+1]);
if(find(j)!=-1) goto out3;
q.push((state){ step+h(j),j});
insert(j,step+1);
}
out3:
if(z%3!=1)
{
swap(d[z],d[z-1]);
ULL j=ToULL(d);
swap(d[z],d[z-1]);
if(find(j)!=-1) continue;
q.push((state){ step+h(j),j});
insert(j,step+1);
}
}
}
int from[],to[];
void work()
{
for(int i=1;i<=9;i++)
scanf("%d",&from[i]);
for(int i=1;i<=9;i++)
scanf("%d",&to[i]);
AStar(from,to);
ULL y=ToULL(to);
printf("%d ",find(y));
#ifdef DEBUG
printf("%d ",clock());
printf("%d ",cnt);
#endif
}
int main()
{
#ifdef DEBUG
freopen("debug.in","r",stdin);
freopen("debug.out","w",stdout);
#endif
work();
return 0;
}
这是基于曼哈顿距离的估价函数的Astar