acwing 845 八数码

这道题很有典型示范意义, 将状态表示为字符串, 进行转移, 还有用到哈希表。

#include <iostream>
#include <queue>
#include <unordered_map>
#include <cstring>
#include <algorithm>

using namespace std;

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

int bfs(string star)
{
    string end = "12345678x";
    
    unordered_map<string, int> hash;
    
    queue<string> q;
    
    q.push(star);
    
    hash[star] = 0;
    
    while(q.size())
    {
        string t = q.front();
        
        q.pop();
        
        int distance = hash[t];
        
        if(t == end) return hash[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(a >= 0 && a < 3 && b >= 0 && b < 3)
            {
                swap(t[k], t[b * 3 + a]);
                if(hash[t] == 0)
                {
                    q.push(t);
                    
                    hash[t] = distance + 1;
                }
                swap(t[k], t[b * 3 + a]);
            }
            
        }
    }
    return -1;
}
int main()
{
    string star;
    for(int i = 0; i < 9; i ++)
    {
        char a;cin >> a;
        star = star + a;
    }
    cout << bfs(star) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值