【八数码】

题目

错误代码

#include<bits/stdc++.h>
using namespace std;
typedef pair<string, int> PII;
#define x first
#define y second

string aim = "12345678x";
int ans = 0x3f3f3f3f;
unordered_map<string, int> m;
void bfs(string s, int pos)
{
    queue<PII> q;
    q.push({s, pos});
    m[s] = 0;
    while(q.size())
    {
        auto u = q.front();
        if(u.x == aim)
        {
            ans = m[u.x];
            return;
        }
        q.pop();
        
        if(u.y - 3 > 0)
        {
            string t = u.x;
            swap(t[u.y], t[u.y-3]);
            if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-3});
        }
        if(u.y + 3 < 9)
        {
            string t = u.x;
            swap(t[u.y], t[u.y+3]);
            if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+3});
        }
        if(u.y/3 == (u.y-1)/3)
        {
            string t = u.x;
            swap(t[u.y], t[u.y-1]);
            if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y-1});
        }
        if(u.y/3 == (u.y+1)/3)
        {
            string t = u.x;
            swap(t[u.y], t[u.y+1]);
            if(!m.count(t)) m[t] = m[u.x]+1, q.push({t, u.y+1});
        }
    }
    
}
int main()
{
    string s = "";
    int pos;
    for(int i = 0; i < 9; i++)
    {
        char c;
        cin >> c;
        if(c == 'x') pos = i;
        s = s + c;
    }
    bfs(s, pos);
    if(ans == 0x3f3f3f3f) ans = -1;
    cout << ans;
    
    return 0;
}

思考

11个样例过5个TLE,我怀疑是复杂度太高了,枚举的速度太慢了。

不能够用字符串操作吗?但是不用字符串用矩阵进行状态存储也不现实啊。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值