图论 八字码

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

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;
}
相关推荐
随意起个昵称2 小时前
线性dp-计数类题目10(ZBRKA)
算法·动态规划
Navigator_Z8 小时前
LeetCode //C - 1089. Duplicate Zeros
c语言·算法·leetcode
cany10008 小时前
C++ -- 可变参数模板
c++
不会C语言的男孩9 小时前
C++ Primer 第2章:变量和基本类型
开发语言·c++
云泽80811 小时前
C++ 可调用对象通关指南:深度解析 Lambda 表达式、function 包装器与 bind 绑定器
开发语言·c++·算法
wlsh1511 小时前
Go 迭代器
算法
Tri_Function11 小时前
简单图论大学习
c++
语戚11 小时前
力扣 3161. 块放置查询:线段树解法(Java 实现)
java·算法·leetcode·面试·线段树·力扣·
lqqjuly12 小时前
C++ 完整知识体系—从基础语法到现代 C++23 的系统性总结
c++·c++23
CS创新实验室12 小时前
从顺序表到动态数组:数据结构的永恒基石与现代语言的优雅封装
数据结构·算法