图论 八字码

我们可能惊异于某些技巧。我们认为这个技巧真是巧妙啊。或者有人认为我依靠自己的直觉想出了这个表示方法。非常自豪。我认为假设是很小的时候,比如说小学初中,还是不错的。到高中大学,就有一些不成熟了。因为这实际上是一个竞技。很多东西前人其实已经总结得非常全面了。这其实对于高手来说是类似常识一样的东西了。我们得尽快地熟练这些东西。这是最重要的事情。重复。这个是一个非常经典的题。有时间的话,可以多写几遍。像是背英语单词一样。一遍肯定是不够的。

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<queue>
#include<unordered_map>

using namespace std;

int bfs(string state){
    queue<string> q;
    unordered_map<string,int> d;
    
    q.push(state);
    d[state]=0;
    
    int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
    string end="12345678x";
    while(q.size()){
        auto t=q.front();
        q.pop();
        
        if(t==end){
            return d[t];
        }
        
        int distance=d[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[a*3+b]);
                if(!d.count(t)){
                    d[t]=distance+1;
                    q.push(t);
                }
                swap(t[k],t[a*3+b]);
            }
        }
    }
    
    return -1;
}

int main(){
    char s[2];
    string state;
    for(int i=0;i<9;i++){
        cin>>s;
        state+=*s;
    }
    
    printf("%d\n",bfs(state));
    
    return 0;
}
相关推荐
Pniubi2 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK2 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司3 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
一拳一个呆瓜4 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso4 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化5 小时前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3
阿庆_AI研发工程师5 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户7341681035486 小时前
基于MindSpore的深度残差收缩网络程序
算法
Pniubi6 小时前
力扣239.滑动窗口最大值(优先队列)
算法·leetcode·职场和发展
eggwyw7 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++