C++ 算法提高 八数码

该博客主要讨论了如何使用宽度优先搜索(BFS)解决RXY八数码问题。通过输入目标和起始状态,程序计算出从起始状态到达目标状态所需的最小步数。在代码实现中,利用了字符串来表示棋盘状态,并通过队列进行广度优先搜索。当找到目标状态时,输出步数。这是一个典型的图搜索问题,适用于优化和路径规划场景。
摘要由CSDN通过智能技术生成

算法提高 八数码

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

RXY八数码

输入格式

输入两个3*3表格
  第一个为目标表格
  第二个为检索表格

输出格式

输出步数

样例输入

1 2 3
4 5 6
7 8 0
1 2 3
4 5 6
7 0 8

样例输出

1

数据规模和约定

332

代码

#include<string>
#include<map>
#include<iostream>
#include<queue>

using namespace std;

int change_x[4]={0,1,0,-1};
int change_y[4]={1,0,-1,0};

int main()
{
    string a,b,temp;
    for(int i=0;i<9;i++)
    {
        cin>>temp;
        a+=temp;
    }
    for(int i=0;i<9;i++)
    {
        cin>>temp;
        b+=temp;
    }
    map<string,int> m;
    m[a]=0;
    queue<string> q;
    q.push(a);
    int distance;
    while(q.size())
    {
        temp = q.front();
        q.pop();
        if(temp==b)
        {
            cout<<m[temp];
            return 0;
        }
        distance=m[temp];
        int index = temp.find('0');
        for(int i=0;i<4;i++)
        {
            int x=index/3+change_x[i];
            int y=index%3+change_y[i];
            if(x>2||x<0||y>2||y<0)
                continue;
            swap(temp[index],temp[x*3+y]);
            if(m.count(temp)==0)
            {
                m[temp]=distance+1;
                q.push(temp);
            }
            swap(temp[index],temp[x*3+y]);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冬眠的int21h

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值