POJ 1077 Eight(神奇的八数码问题)

本文介绍了一种使用哈希和优先队列结合广度优先搜索(BFS)来解决8数码问题的方法。通过定义合适的哈希函数和优先级,确保了算法能够有效地找到问题的解决方案。此外,还提供了一个具体的实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


八数码问题是个很神奇的问题,方法有很多

暂时会一种(哈希+优先队列+bfs)

#include<cstring>
#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int ha[10]={0,2,3,5,11,41,131,721,5041,40321};
int dx[]={0,0,0,-1,1},dy[]={0,1,-1,0,0},a[10];
int used[2000000],tot;
int bs(int x)
{
    if(x<0)return -x;
    return x;
}
struct Node
{
    int ma[4][4],h,g,ha,x,y;
    string str;   //队友告诉我用字符串更方便 果断换递归输出为string记录输出
    bool operator<(const Node a)const
    {
        if(h==a.h)
            return g>a.g;
        return h>a.h;
    }
};
int getha(Node c)//哈希函数
{
    int k,ans=0;
    int aa[11];
    for(int i=1;i<=9;i++)
        aa[i]=c.ma[(i+2)/3][(i-1)%3+1];
    for(int i=1;i<=9;i++)
    {
        k=0;
        for(int j=1;j<=i;j++)
            if(aa[i]<aa[j])
            k++;
        ans+=(k*ha[i]);
    }
    return ans;
}
int geth(Node c)// h优先 h越小距离答案越近 想想为什么
{
    int ans=0;
    for(int i=1;i<=3;i++)
        for(int j=1;j<=3;j++)
    {
        ans=ans+bs((c.ma[i][j]+2)/3-i)+bs((c.ma[i][j]-1)%3+1-j);
    }
    return ans;
}
string f(int x)
{
    if(x==1) return "r";
    else if(x==2) return "l";
    else if(x==3) return "u";
    else if(x==4) return "d";
}
string bfs()
{
    memset(used,0,sizeof(used));
    priority_queue<Node> que;
    Node qq;
    for(int i=1;i<=9;i++)
        qq.ma[(i+2)/3][(i-1)%3+1]=a[i];
    qq.x=(a[0]+2)/3,qq.y=(a[0]-1)%3+1;
    qq.g=tot++;
    qq.ha=getha(qq);
    qq.h=geth(qq);
    if(qq.h==0)
        return "";
    qq.str="";
    que.push(qq);
    used[qq.ha]=1;
    while(!que.empty())
    {
        Node start=que.top();
        que.pop();
        {//for(int i=1;i<=3;i++)
           // for(int j=1;j<=3;j++)
             //   printf("%d ",start.ma[i][j]);
          // printf("\n");}
        for(int i=1;i<=4;i++)
        {
            Node next=start;
            next.x=start.x+dx[i];
            next.y=start.y+dy[i];
            if(next.x<=3&&next.x>0&&next.y<=3&&next.y>0)
            {
                swap(next.ma[start.x][start.y],next.ma[next.x][next.y]);

                next.ha=getha(next);
                if(!used[next.ha])
                {
                used[next.ha]=1;
                next.str=start.str+f(i);
                next.h=geth(next);
                if(next.h==0)
                {
                    //for(int i=1;i<=3;i++)
                      //  for(int j=1;j<=3;j++)
                       // printf("%d ",next.ma[i][j]);
                       // printf("\n");
                    return next.str;
                }
                next.g=tot++;
                que.push(next);
                }
            }
        }

        }

   }
}

int main()
{
          char ch;
    while(scanf(" %c",&ch)!=EOF)
    {
        tot=0;
        if(ch=='x'){a[1]=9;a[0]=1;}
        else a[1]=ch-'0';
        for(int i=2;i<=9;i++)
        {
            scanf(" %c",&ch);
            if(ch=='x'){a[i]=9;a[0]=i;}
            else a[i]=ch-'0';
        }
        int sum=0;
        for(int i=1;i<=9;i++)
            {if(a[i]==9)continue;
                for(int j=1;j<i;j++)
        {if(a[j]==9)continue;
            if(a[i]>a[j])
                sum++;
        }
            }
        if(sum%2)//有一个规律  除x外的  所有状态只有逆序对奇偶性相同 才能互相到达
            printf("unsolvable");
        else
        { string aa=bfs();
            cout<<aa;
        }
        printf("\n");
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值