八数码难题-rqnoj-70

本文介绍了一种使用广度优先搜索解决八数码问题的方法。通过定义节点结构、利用队列进行状态扩展,并采用哈希表避免重复状态,最终实现从初始状态到目标状态的有效路径寻找。

虽然是一道搜素,但还是有点麻烦。因为是求最优解,所以用到了队列,判重用哈希,就把状态看成一个九位数,用“map”不会超内存。


#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;

struct node
{
    int state[9];
    int step;
};

node start,target;
queue<node> q;
map<int,int>hash;


void init()
{
    freopen("input.in","r",stdin);
    freopen("output.txt","w",stdout);
}

int gethash(node st)
{
    int s=0;
    for (int i=0;i<9;i++) s=s*10+st.state[i];
    return s;
}

void readdata()
{
    char s[]="123804765";
    for (int i=0;i<9;i++)target.state[i]=s[i]-'0';
    //for (int i=0;i<9;i++)sscanf(s+i,"%1d",&target.state[i]);
    for (int i=0;i<9;i++)scanf("%1d",&start.state[i]);
    start.step=0;
    q.push(start);
    hash[gethash(start)]=1;

}

bool trytoinsert(node st)
{
    int h=gethash(st);
    if (hash[h]) return false;
    hash[h]=1;
    return true;
}

void check(node st)
{
    if (gethash(st)==gethash(target))
    {
        printf("%d\n",st.step);
        exit(0);
    }
}

int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};

void work()
{
    while(!q.empty())
    {
        node cur=q.front();
        q.pop();
        for (int i=0;i<4;i++)
        {
            node st;
            memcpy(&st,&cur,sizeof(cur));
            int zero=0;
            for (zero=0;st.state[zero]!=0;zero++);
            int x=zero/3;
            int y=zero%3;
            int newx=x+dx[i];
            int newy=y+dy[i];
            if (newx<0 || newx>2 || newy<0 || newy>2) continue;
            int newzero=newx*3+newy;
            st.state[zero]=st.state[newzero];
            st.state[newzero]=0;
            st.step++;
            check(st);
            if (trytoinsert(st)) q.push(st);
        }
    }
}

int main()
{
    //init();
    readdata();
    work();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值