BFS - AcWing 845. 八数码(C++)- 中等

题目链接:https://www.acwing.com/problem/content/description/847/
题目如下:
在这里插入图片描述
在这里插入图片描述

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

using namespace std;

int bfs(string start){
    string end="12345678x";
    
    queue<string> que;//用来记录每次变换后的状态
    unordered_map<string,int> umap;//记录从最开始,到最后目标状态,每一转换的顺序次数
    
    que.push(start);
    umap[start]=0;
    
    while(que.size()){
        auto t=que.front();
        que.pop();
        
        int distance=umap[t];
        if(t==end) return distance;
        
        //状态转移
        int pos=t.find('x');//返回字符x所在string中的位置
        int x=pos/3,y=pos%3;
        
        int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
        for(int i=0;i<4;i++){
            int a=x+dx[i];
            int b=y+dy[i];
            
            if(a>=0&&a<3&&b>=0&&b<3){
                swap(t[pos],t[a*3+b]);//当前x向其他方向走动
                
                if(umap[t]==0){//用来判断umap中是否已经存有t,如果更新过的t没有更新过,则找到了一个新的状态
                    umap[t]=distance+1;
                    que.push(t);
                }
                
                swap(t[pos],t[a*3+b]);//这里要恢复状态,因为要对下一个方向做判断,看能不能转换,因为四个方向遍历算作一次操作
            }
        }
    }
    
    return -1;
}
int main(){
    string start="";
    for(int i=0;i<9;i++){
        char c;
        cin>>c;
        start+=c;
    }
    
    cout<<bfs(start)<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值