栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

移动玩具(状态压缩 + 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 
#include 
#include 
#include 
#include 
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 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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722620.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号