您的位置:首页 > 其它

[HDOJ3567]Eight II

2011-04-25 11:26 232 查看
八数码问题,IDA*解~

View Code

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int SIZE = 365000;
const int LEN = 10;
const int move[][5] = {{2,3,1},{3,4,0,2},{2,5,1},{3,6,4,0},{4,7,3,5,1},{3,8,4,2},{2,7,3},{3,6,8,4},{2,7,5}};
const char moves[][8] = {"dr","dlr","dl","dru","dlru","dlu","ru","lru","lu"};
const int DIST[][LEN] =
{
{0,1,2,1,2,3,2,3,4},
{1,0,1,2,1,2,3,2,3},
{2,1,0,3,2,1,4,3,2},
{1,2,3,0,1,2,1,2,3},
{2,1,2,1,0,1,2,1,2},
{3,2,1,2,1,0,3,2,1},
{2,3,4,1,2,3,0,1,2},
{3,2,3,2,1,2,1,0,1},
{4,3,2,3,2,1,2,1,0}
};

char org[LEN];
char des[LEN];

char output[SIZE];

int maxstep;

int Estimate(char * key)
{
int value = 0;
for (int i = 0;i < LEN - 1;i++)
if (key[i] != '0')
value += DIST[i][strchr(des,key[i])-des];
return value;
}

bool IDAstar(int now,int pos,int pre)
{
int need = Estimate(org);
if (now + need > maxstep) return false;

if (need == 0)
{
printf("%d\n",now);
output[now] = '\0';
printf("%s\n",output);
return true;
}

for (int i = 1;i <= move[pos][0];i++)
{
int npos = move[pos][i];

if (npos == pre) continue;

swap(org[pos],org[npos]);
output[now] = moves[pos][i-1];
if (IDAstar(now + 1,npos,pos)) return true;
swap(org[pos],org[npos]);
}
return false;
}

int main()
{
//freopen("1.in","r",stdin);
//freopen("out.txt","w",stdout);

int cas;
int idx;

scanf("%d",&cas);

for (int cc = 0;cc < cas;cc++)
{
scanf("%s",org);
for (int i = 0;i < LEN - 1;i++)
if (org[i] == 'X')
{
idx = i;
org[i] = '0';
}

scanf("%s",des);
for (int i = 0;i < LEN - 1;i++)
if (des[i] == 'X')
des[i] = '0';

printf("Case %d: ",cc + 1);

for (maxstep = Estimate(org);;maxstep++)
if (IDAstar(0,idx,-1))
break;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: