经典搜索题目——八数码

#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;

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

bool inmp(int x,int y)
{
    return x>=0&&x<3&&y>=0&&y<3;
}

int bfs(string str)
{
    queue<string> q;
    unordered_map<string,int> d;
    // 哈希表存储出现过的字符串
    q.push(str);
    d[str]=0;
    string end = "12345678x";
    while(!q.empty())
    {
        auto t = q.front();
        q.pop();
        if(t==end) return d[t];
        int dist = d[t];
        int k = t.find('x');
        int x =k/3,y=k%3;
        // 一维变二维的做法
        for(int i=0;i<4;i++)
        {
            int a =x+dx[i],b=y+dy[i];
            if(inmp(a,b))
            {
                swap(t[a*3+b],t[k]);
                if(!d[t])
                {
                    d[t] = dist+1;
                    q.push(t);
                }
                swap(t[a*3+b],t[k]);
            }
        }
    }
    return -1;
}

int main(void)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    string str;
    for(int i=0;i<9;i++)
    {
        char c;cin >> c;
        str+=c;
    }
    cout << bfs(str) << endl;
    return 0;
}

感谢查看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值