经典搜索题目——八数码

#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

bool inmp(int x,int y)
{
    return x>=0&&x<3&&y>=0&&y<3;
}

int bfs(string str)
{
    queue<string> q;
    unordered_map<string,int> d;
    // 哈希表存储出现过的字符串
    q.push(str);
    d[str]=0;
    string end = "12345678x";
    while(!q.empty())
    {
        auto t = q.front();
        q.pop();
        if(t==end) return d[t];
        int dist = 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(inmp(a,b))
            {
                swap(t[a*3+b],t[k]);
                if(!d[t])
                {
                    d[t] = dist+1;
                    q.push(t);
                }
                swap(t[a*3+b],t[k]);
            }
        }
    }
    return -1;
}

int main(void)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    string str;
    for(int i=0;i<9;i++)
    {
        char c;cin >> c;
        str+=c;
    }
    cout << bfs(str) << endl;
    return 0;
}

感谢查看

相关推荐

  1. C++经典面试题目

    2024-04-21 16:42:02       45 阅读
  2. C语言经典面试题目

    2024-04-21 16:42:02       50 阅读
  3. C语言经典面试题目(十

    2024-04-21 16:42:02       42 阅读
  4. C++经典面试题目(十

    2024-04-21 16:42:02       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-21 16:42:02       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-21 16:42:02       107 阅读
  3. 在Django里面运行非项目文件

    2024-04-21 16:42:02       90 阅读
  4. Python语言-面向对象

    2024-04-21 16:42:02       98 阅读

热门阅读

  1. Spark面试整理-Spark集成Kafka

    2024-04-21 16:42:02       31 阅读
  2. Redis如何查看KEY的数据类型

    2024-04-21 16:42:02       38 阅读
  3. C语言整型提升

    2024-04-21 16:42:02       37 阅读
  4. C++ 面向对象

    2024-04-21 16:42:02       37 阅读
  5. 信息收集分类

    2024-04-21 16:42:02       36 阅读
  6. 笔记:Python编程题 练习题

    2024-04-21 16:42:02       37 阅读
  7. Ansible 连接受控端sudo超时

    2024-04-21 16:42:02       31 阅读
  8. SQL书写顺序与执行顺序

    2024-04-21 16:42:02       32 阅读
  9. 力扣704/35/34:二分查找

    2024-04-21 16:42:02       37 阅读
  10. transformer学习

    2024-04-21 16:42:02       30 阅读