【HDU 1043】Eight(A*启发式搜索算法)

Description

The 15-puzzle has been around for over 100 years; even if you don’t know it by that name, you’ve seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let’s call the missing tile ‘x’; the object of the puzzle is to arrange the tiles so that they are ordered as:

 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15  x

where the only legal operation is to exchange ‘x’ with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:

 1  2  3  4     1  2  3  4     1  2  3  4     1  2  3  4
 5  6  7  8     5  6  7  8     5  6  7  8     5  6  7  8
 9  x 10 12     9 10  x 12     9 10 11 12     9 10 11 12
13 14 11 15    13 14 11 15    13 14  x 15    13 14 15  x
            r->            d->            r->

The letters in the previous row indicate which neighbor of the ‘x’ tile is swapped with the ‘x’ tile at each step; legal values are ‘r’,’l’,’u’ and ‘d’, for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing ‘x’ tile, of course).

In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.

Input

You will receive, several descriptions of configuration of the 8 puzzle. One description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus ‘x’. For example, this puzzle

1 2 3
x 4 6
7 5 8

is described by this list:

1 2 3 x 4 6 7 5 8

Output

You will print to standard output either the word “unsolvable”, if the puzzle has no solution, or a string consisting entirely of the letters ‘r’, ‘l’, ‘u’ and ‘d’ that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line. Do not print a blank line between cases.

Sample Input

2 3 4 1 5 x 7 6 8

Sample Output

ullddrurdllurdruldr

题目大意

这题其实和我们经常玩的一个游戏非常的像,看下图:
【HDU 1043】Eight(A*启发式搜索算法)_第1张图片
不过这边所要拼成的目标是这样的;

1 2 3
4 5 6
7 8 x

题目就是给你任意一个中间的转态,问你怎样移动x(x就相当于图中的白块,可以和相邻块交换。)能到达目标转态。其实这就是一个八数码的经典问题。

思路

八数码问题以及各种实现方法和讲解可以见:http://blog.csdn.net/huangxy10/article/details/8034285
对于这题我把大部分思路都写在了代码注释里,因为A*算法在一定程度上比较难以理解,所以我觉得结合代码大家应该更看的懂,我自己也是看了3天的A*算法后才勉强可以做这题的。在这里我先简要讲一讲这题:
首先这题必须要用hash和康托展开来压缩空间,康托展开的原理我用一个例子来讲解:
对于这样一个排列:14032,他在排列中排第几呢?公式是:
1*4!+3*3!+0*2!+1*1!+0*0!
求法是这样的,首先看第一个数字1,在数字1前面(不是这个排列的前面,而是这个排列所出现的数字中,如14032中只有一个0比它小)小于它的数只有一个0,对于它后面的数可以有4!种(4的全排列),所以对于1就是1*4!,同理对于4,0~4比它小的有0,1,2,3,但是1在前面已经用过了,所以只有3个,对于后面就是3!,所以对于4就是3*3!,同理往后推。

但是为什么要用hash呢,其实就是为了判重,因为如果你用普通的方法去判重,那么对于3*3方块,每一个数字都有9种可能0~8,况且你用普通bfs和dfs的vis数组根本无法判这题状态是否重复。但是hash可以很好的解决这个问题,因为hash可以把3*3这些数字全部排列的个数控制在0~9!上,对于每一个转态就有一个唯一的hash值,此时只要开一个一维的vis[hash最大值]数组就可以判重。

其次这题所用的A*算法见:http://blog.csdn.net/huangxy10/article/details/8034285

代码

#include 
#include 
#include 
#include 
#include 

using namespace std;
const int maxn=4e5+10;

int ha[9]={1,1,2,6,24,120,720,5040,40320};
/*这个ha[9]数组是用来计算hash值的,这个数组中的值分别是0!,1!,2!,3!,4!,5!,6!,7!,8!*/
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char d[10]="udlr";
int vis[maxn];//判重 

struct proc
{
    int f[3][3];//当前这个转态每个位置上的值 
    int x,y;
    int g,h;
    int hash_num;
    bool operator < (const proc a)const
    {
        return h+g>a.h+a.g;//优先队列保证 出队的是估值函数值较小的。 
    }
};

struct path
{
    int pre;
    char ch;
}p[maxn];//用于记录路径 


//评估函数,获得评估值  
//计算1~8的数字回到原点需要的步数作为评估值,必定小于实际操作数  
int get_h(proc a)
{
    int i,j,ans=0;
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            if(a.f[i][j])
            {
                ans+=abs(i-(a.f[i][j]-1)/3)+abs(j-(a.f[i][j]-1)%3);//曼哈顿距离
            }
        }
    }
    return ans;
}

//康托展开 
int get_hash(proc e)
{
    int a[9],i,j,k=0,ans=0;  
    for(i=0;i<3;i++) //将数据排成一排,便于计算 
    {  
        for(j=0;j<3;j++)  
            a[k++]=e.f[i][j];  
    }  
    for(i=0;i<9;i++)//计算hash值  
    {  
        k=0;  
        for(j=0;jif(a[j]>a[i])k++; 
        ans+=ha[i]*k;  
    }  
    return ans;  
}

void print(int x)
{
    if(p[x].pre==-1) return;
    print(p[x].pre);
    printf("%c",p[x].ch);
}

void A_star(proc a)
{
    memset(vis,0,sizeof(vis));
    int end_ans,xx,yy,k;
    proc vw,vn;
    for(int i=0;i<9;i++)
    {
        vw.f[i/3][i%3]=(i+1)%9;//目标转态时各个位置的值
    }
    end_ans=get_hash(vw);//目标转态时的hash值
    a.hash_num=get_hash(a);
    a.g=0;a.h=get_h(a);
    vis[a.hash_num]=1;
    p[a.hash_num].pre=-1;
    if(a.hash_num==end_ans)
    {
        printf("\n");
        return;
    }
    priority_queue q;
    q.push(a);
    while(!q.empty())
    {
        a=q.top();
        q.pop();
        for(int i=0;i<4;i++)
        {
            xx=a.x+dir[i][0];
            yy=a.y+dir[i][1];
            if(xx<0||yy<0||xx>=3||yy>=3) continue;
            vw=a;
            swap(vw.f[a.x][a.y],vw.f[xx][yy]);//交换双方的值
            k=get_hash(vw);
            if(vis[k]) continue;
            vis[k]=1;
            vw.hash_num=k;
            vw.x=xx;
            vw.y=yy;
            vw.g++;
            vw.h=get_h(vw);
            p[k].pre=a.hash_num;
            p[k].ch=d[i];
            if(k==end_ans)//如果当前状态的hash值等于目标状态的hash值,表示已经到达目标状态
            {
                print(k);
                printf("\n");
                return;
            }
            q.push(vw);
        }
    }
}

int main()
{
    char a[30];  
    while(gets(a))  
    {  
        int i,j,k,n;  
        proc e;  
        n=strlen(a);  
        for(i=0,j=0;iif(a[i]==' ')continue;  
            if(a[i]=='x'){e.f[j/3][j%3]=0;e.x=j/3;e.y=j%3;}  
            else e.f[j/3][j%3]=a[i]-'0';  
            j++;  
        }   
        for(i=0,k=0;i<9;i++)  //这边涉及到一个逆序数问题,如果开始状态的逆序数为奇数,那么这个状态只能到达逆序数为奇数的转态,同理偶数逆序数的状态也只能到达逆序数为偶数的状态
        {  
            if(e.f[i/3][i%3]==0)continue;  
            for(j=0;jif(e.f[j/3][j%3]==0)continue;  
                if(e.f[j/3][j%3]>e.f[i/3][i%3])k++;  
            }  
        }  
        if(k&1)printf("unsolvable\n");  
        else A_star(e);  
    }  
    return 0;    
}

你可能感兴趣的:(ACM)