八数码题解

179. 八数码 - AcWing题库

首先要明确八数码问题的小结论,当原始序列中逆序对数列为奇数时一定无解,反之一定有解。

解法一:BFS+A*

首先思考用纯BFS解决这个问题。

大致的框架就是:

队列q,状态数组dist,上个状态prev
while(q.size())
{
    int t=q.front();
    q.pop();
    if(t==目标) break;
    找出x的位置
    for(枚举x在上下左右四个方向移动)
    {
        if(超出范围) continue;
        if(当前状态没被遍历||当前距离<之前距离)
        {
            q.push(当前状态);
            更新dist;
        }
    }
}

while(end!=start)
{
    遍历前序状态数组记录操作;
}
输出

这样子会超时。其实有点不明白为什么会超时,状态数是9!,1e5级别的,我算错了吗?

然后思考,可以用A*优化,其实就是加一个代价函数。

代价函数如下:

int f(string state)
{
    计算state到目标状态的曼哈顿距离
}

写代码时本人有几个小细节容易出错:

①计算逆序对数量时,忘记跳过x

ac代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
#define x first
#define y second
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
char op[5]={'u','d','l','r'};
string tag="12345678x";
string str;
int f(string s)
{
    int res=0;
    for(int i=0;i<9;i++)
    {
        if(s[i]!='x')
        {
            int t=s[i]-'1';
            res+=abs(t/3-i/3);
            res+=abs(t%3-i%3);
        }
    }
    return res;
}
void bfs(string s)
{
    unordered_map<string,int> dist;
    unordered_map<string,pair<string,char>> prev;
    priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> q;
    
    q.push({f(s),s});
    dist[s]=0;
    while(q.size())
    {
        auto t=q.top();
        q.pop();
        string state=t.y;
        int step=dist[state];
        if(state==tag) break;
        int x=-1,y=-1;
        for(int i=0;i<9;i++)
            if(state[i]=='x')
            {
                x=i/3,y=i%3;
                break;
            }
        for(int i=0;i<4;i++)
        {
            int cx=x+dx[i],cy=y+dy[i];
            if(cx<0||cx>=3||cy<0||cy>=3) continue;
            string temp=state;
            swap(temp[3*x+y],temp[3*cx+cy]);
            if(!dist.count(temp)||dist[temp]>step+1)
            {
                dist[temp]=step+1;
                q.push({dist[temp]+f(temp),temp});
                prev[temp]={state,op[i]};
            }
        }
    }
    vector<char> res;
    while(tag!=s)
    {
        res.push_back(prev[tag].y);
        tag=prev[tag].x;
    }
    reverse(res.begin(),res.end());
    for(int i=0;i<res.size();i++) cout<<res[i];
}
int main()
{
    char c;
    while(cin>>c) str+=c;
    int cnt=0;
    for(int i=0;i<9;i++)
        for(int j=i+1;j<9;j++)
        {
            if(str[i]=='x') i++;
            if(str[j]=='x') j++;
            if(str[i]-'1'>str[j]-'1') cnt++;
        }
    if(cnt%2) cout<<"unsolvable";
    else bfs(str);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值