八数码 bfs

在这里插入图片描述
代码:

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <unordered_map>    //map有序,内部红黑树,查找效率低,会T
                            //unordered_map内部哈希表,查找速度快,常用于查找问题
using namespace std;
int mov[4][2]={0,1,1,0,0,-1,-1,0};

void bfs(string st)
{
    string ed="12345678x";
    queue<string> q;    //存放矩阵状态
    unordered_map<string,int> dis;  //从初始状态变为k状态需要dis[k]次交换
    dis[st]=0;
    q.push(st);
    
    while(!q.empty())
    {
        string nst=q.front();
        q.pop();
        
        int ndis=dis[nst];  //当前交换次数
        if(nst==ed)
        {
            cout<<ndis<<endl;
            return ;
        }
        
        int k=nst.find('x');    //find函数返回字符串nst中x的下标
        int x=k/3,y=k%3;        //在3×3矩阵中的横纵坐标
        
        for(int i=0;i<4;i++)
        {
            int tx=x+mov[i][0];
            int ty=y+mov[i][1];
            
            if(tx<0||tx>2||ty<0||ty>2)  continue;   //越界跳过
            
            swap(nst[k],nst[3*tx+ty]);  //交换x与新的可交换点的位置(此时nst变为了一个新的字符串)
            //count函数返回容器中value出现的次数
            //queue不可用 对于map,count返回值为0或1
            if(!dis.count(nst))     //如果该状态第一次出现
            {
                dis[nst]=ndis+1;    
                q.push(nst);
            }
            swap(nst[k],nst[3*tx+ty]);  //恢复状态
        }
    }
    
    cout<<-1<<endl; //不存在解决方案
    return ;
}

int main()
{
    string t,st=""; //string类型存放矩阵状态
    for(int i=1;i<=9;i++)
    {
        cin>>t;
        st+=t;
    }
    bfs(st);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值