移动玩具(状态压缩 + bfs)

原题链接

题目描述

具向上下左右四个方向移动,并且移动的位置不能有玩具,请你用最少的移动次数将初始的玩具状态移动到某人心中的目标状态。

输入样例
1111
0000
1110
0010 

1010
0101
1010
0101

####输出样例

4

(状态压缩 + bfs) O ( n 2 ) O(n^2) O(n2)

由于本题只有01两种数字,且只有16个元素,所以可以将这个二维数足状压成二进制来做。

在移动过程中,可以想到,我们可以先用 0 覆盖掉移动的位置,再将 1 插入,这一方法我们可以用位运算的方式实现。

参考文献 点击链接
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 1e6 + 10;
const int f[4][4]= {{15,14,13,12},{11,10,9,8},{7,6,5,4},{3,2,1,0}};//状态位
queue<int> q;
struct St
{
    int step;//储存出现次数
    bool book;//储存是否出现过
}a[N];
int num,ed;//初始状态和目标状态

int moving(int now,int x,int y,bool next)
{
    int t1 = now & (1 << f[x][y]),t2 = now & (1 << f[x + next][y + (!next)]);

    return (now & (~t1) & (~t2)) | (t1 >> f[x][y] << f[x + next][y + (!next)]) | (t2 >> f[x + next][y + (!next)] << f[x][y]);
}
bool Push(int x,int y,bool next)
{
    int t = moving(q.front(),x,y,next);//t 储存移动后状态
    if(t == ed)//如果移动后为目标状态
    {
        cout << a[q.front()].step + 1 << '\n';//输出移动步数
        return true;//返回真,表示已经搜索到了目标状态
    }
    if(a[t].book)//如果该状态没有被标记过(即没有搜索到过)
        return false;//返回假,表示没有搜索到目标状态

    q.push(t);//入队
    a[t].step = a[q.front()].step + 1;//移动次数比原来多1
    a[t].book=true;//给该状态打上标记

    return false;//返回假,表示没有搜索到目标状态
}
void bfs()
{
    //bfs搜索每位
    while(q.size()){
        for(int i = 0;i < 4;i ++ )
            for(int j = 0;j < 3;j ++ ){
                if(Push(i,j,false))
                    return;
                else if(Push(j,i,true))
                    return;
            }
        q.pop();
    }
}
int main()
{
    string s;
    for (int i = 0;i < 4;i ++) {
        cin >> s;
        for (char it : s) num = (num << 1) | (it - '0');//二进制往后直接加一个数
    }
    q.push(num);//输入初始状态并入队
    a[q.front()].book = true;//打上标记

    for (int i = 0;i < 4;i ++) {
        cin >> s;
        for (char it : s) ed = (ed << 1) | (it - '0');//二进制往后直接加一个数
    }
    if (q.front() == ed) {
        puts("0");
        return 0;
    }

    bfs();

    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

marvel121

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

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

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

打赏作者

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

抵扣说明:

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

余额充值