算法.bfs八数码

cpp 复制代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
int bfs(string state)
{
    queue<string>q;
    unordered_map<string, int>d;
    q.push(state);
    d[state] = 0;
    while (q.size())
    {
        auto t = q.front();

        int dis = d[t];
        int k = t.find('x');
        int x = k / 3, y = k % 3;

        q.pop();
        string end = "12345678x";
        if (t == end)return d[t];
        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[a * 3 + b], t[k]);
                if (!d.count(t))
                {
                    d[t] = dis + 1;
                    q.push(t);
                }
                swap(t[a * 3 + b], t[k]);
            }
            
        }
    }
    
    return -1;
}

int main()
{
    string state;
    for (int i = 0; i < 9; i++)
    {
        char s;
        cin >> s;
        state += s;
    }
    cout << bfs(state);
    return 0;
}
相关推荐
2401_8414956415 分钟前
【LeetCode刷题】寻找重复数
数据结构·python·算法·leetcode·链表·数组·重复数
罗技12332 分钟前
Easysearch 集群监控实战(下):线程池、索引、查询、段合并性能指标详解
前端·javascript·算法
一路往蓝-Anbo33 分钟前
C语言从句柄到对象 (七) —— 给对象加把锁:RTOS 环境下的并发安全
java·c语言·开发语言·stm32·单片机·嵌入式硬件·算法
中國龍在廣州41 分钟前
谈谈2025年人工智能现状及发展趋势分析
人工智能·深度学习·算法·自然语言处理·chatgpt·机器人·机器人学习
C雨后彩虹1 小时前
二维伞的雨滴效应
java·数据结构·算法·华为·面试
youngee112 小时前
hot100-60子集
数据结构·算法
郝学胜-神的一滴2 小时前
Linux线程属性设置分离技术详解
linux·服务器·数据结构·c++·程序人生·算法
Timmylyx05182 小时前
2025年最后一搏—— Educational Codeforces Round 186 (Rated for Div. 2) 题解
算法·codeforces·比赛日记
微光闪现2 小时前
国际航班动态提醒与延误预测优选平台指南
大数据·人工智能·算法
leoufung2 小时前
LeetCode 120. Triangle:从 0 分到 100 分的思考过程(含二维 DP 与空间优化)
linux·算法·leetcode