AcWing打卡题:八数码问题

八数码问题

#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <string>
using namespace std;
const int maxsize = 10;

int exchange_min(string start)
{
    queue<string> q;                                        //队列实现bfs
    unordered_map<string, int> dist;                          //哈希表,表示从初始状态到新的状态的最短距离
    string end = "12345678x";                               //结束状态
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};       //'x'可以移动的位置,上下左右4个方向
    q.push(start);                                          //入队
    dist[start] = 0;                                        //初始化
    while(!q.empty())
    {
        auto temp = q.front();
        q.pop();
        int distance = dist[temp];
        if(temp == end) return distance;
        
        int k = temp.find('x');                 //返回x的位置,从0开始
        int x = k / 3, y = k % 3;               //计算x的二维坐标,即恢复为3*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(temp[k], temp[a * 3 + b]);          //交换位置,形成新的状态
                if(!dist.count(temp))                   //如果新的状态的距离为0
                {
                    dist[temp] = distance + 1;          //更新距离,distance是未更新距离
                    q.push(temp);                       //将新的状态入队;
                }
                swap(temp[k], temp[a * 3 + b]);         //恢复未移动的状态
            }
        }
        
    }
    
    return -1;                                          //遍历到最后也没返回即不存在解决方案
    
}

int main()
{
    char c;
    string str;
    for(int i = 0; i < 9; i++)
    {
        cin >> c;
        str += c;
    }
    
    cout << exchange_min(str) << endl;
    return 0;
        
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值