845. 八数码

这篇文章描述了一个使用深度优先搜索(DFS)的方法,解决一个涉及字符串操作和矩阵移动的问题,目标是从给定的初始状态到达12345678x状态,记录最少步数。
摘要由CSDN通过智能技术生成

#include<bits/stdc++.h>

using namespace std;
string s;
queue<string> q;
unordered_map<string,int> d;//记录到达当前状态需要移动的步数

int bfs()
{
    string end = "12345678x";//结束时的状态
    q.push(s);//把字符串s放入队列
    d[s] = 0;//记录到达当前状态的步数,因为是初始状态,步数为0
    
    int dx[4] = {-1,0,+1,0},dy[4] = {0,+1,0,-1};
    
    while(q.size())
    {
        string a = q.front();//取出队头
        q.pop();//删除队头
        int distance = d[a];
        if(a == end) return distance;
        
        int position = a.find('x');//找到字符x在字符串中的位置
        int x1 = position / 3,y1 = position % 3;//找到x在矩阵中的位置
        for(int i = 0; i < 4; i ++)
        {
            //向四个方向移动
            int x = x1 + dx[i],y = y1 + dy[i];
            if(x >= 0 && x < 3 && y >= 0 && y < 3)
            {
                swap(a[position],a[x * 3 + y]);
                if(!d.count(a))//该状态是第一次找到
                {
                    d[a] = distance + 1;
                    q.push(a);//将转变为之后的字符串放入
                }
                swap(a[position],a[x * 3 + y]);//恢复现场
            }
        }
    }
    return -1;//找不到结果
}

int main()
{
    for(int i = 0; i < 9; i ++)
    {
        char c;
        cin >> c;
        s += c;//得到初始状态字符串
    }
    
    cout << bfs() << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值