栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

题目链接:https://www.acwing.com/problem/content/description/847/
题目如下:

#include 
#include 
#include 
#include 

using namespace std;

int bfs(string start){
    string end="12345678x";
    
    queue que;//用来记录每次变换后的状态
    unordered_map 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<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890452.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号