POJ - 1077 Eight(A∗算法)

POJ - 1077 Eight(A∗算法)

在这里插入图片描述
在这里插入图片描述

#include<iostream>
#include<algorithm>
#include<map>
#include<queue>

#define x first
#define y second

using namespace std;

typedef pair<int,string> PIS;
typedef pair<char,string> PCS;

int f(string state)
{
    int res=0;
    for(int i=0;i<9;i++)
        if (state[i]!='x')
        {
            int v=state[i]-'1';
            res+=abs(v/3-i/3)+abs(v%3-i%3);
        }
    return res;
}

string bfs(string start)
{
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    char op[5] = "urdl";

    string end="12345678x";
    map<string,int> dist;
    map<string,pair<char,string> >pre;
    priority_queue<PIS,vector<PIS>,greater<PIS> >heap;

    heap.push((PIS){f(start), start});
    dist[start]=0;

    while(heap.size())
    {
        PIS t=heap.top();heap.pop();

        string state=t.y;
        if(state==end) break;

        int x,y;
        for(int i=0;i<9;i++)
            if(state[i]=='x')
            {
                x=i/3,y=i%3;
                break;
            }
        string source=state;
        for (int i=0;i<4;i++)
        {
            int a=x+dx[i],b=y+dy[i];
            if(a<0||a>=3||b<0||b>=3) continue;
            state=source;
            swap(state[x*3+y],state[a*3+b]);
            if (dist.count(state)==0||dist[state]>dist[source]+1)
            {
                dist[state]=dist[source]+1;
                pre[state] =(PCS){op[i],source};
                heap.push((PIS){dist[state]+f(state),state});
            }
        }
    }
    string res;
    while(end!=start)
    {
        res+=pre[end].x;
        end=pre[end].y;
    }
    reverse(res.begin(),res.end());
    return res;
}

int main()
{
    string start,seq,c;
    while(cin>>c)
    {
        start+=c;
        if(c!="x") seq+=c;
    }

    int cnt=0;
    for(int i=0;i<8;i++)
        for(int j=i+1;j<8;j++)
            if(seq[i]>seq[j])
                cnt++;

    if(cnt%2) cout<<"unsolvable"<<endl;
    else cout<<bfs(start)<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wa_Automata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值