算法.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;
}
相关推荐
算法鑫探4 小时前
闰年判断:C语言实战解析
c语言·数据结构·算法·新人首发
WBluuue4 小时前
数据结构与算法:康托展开、约瑟夫环、完美洗牌
c++·算法
木子墨5164 小时前
LeetCode 热题 100 精讲 | 并查集篇:最长连续序列 · 岛屿数量 · 省份数量 · 冗余连接 · 等式方程的可满足性
数据结构·c++·算法·leetcode
王老师青少年编程5 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:均分纸牌
c++·算法·编程·贪心·csp·信奥赛·均分纸牌
EQUINOX15 小时前
2026年码蹄杯 本科院校赛道&青少年挑战赛道提高组初赛(省赛)第一场,个人题解
算法
萝卜小白5 小时前
算法实习Day04-MinerU2.5-pro
人工智能·算法·机器学习
Liangwei Lin5 小时前
洛谷 P3133 [USACO16JAN] Radio Contact G
数据结构·算法
weixin_513449966 小时前
PCA、SVD 、 ICP 、kd-tree算法的简单整理总结
c++·人工智能·学习·算法·机器人
code_pgf6 小时前
Qwen2.5-VL 算法解析
人工智能·深度学习·算法·transformer
Code-keys6 小时前
Android Codec2 Filter 算法模块开发指南
android·算法·音视频·视频编解码