原题链接
题目描述
具向上下左右四个方向移动,并且移动的位置不能有玩具,请你用最少的移动次数将初始的玩具状态移动到某人心中的目标状态。
输入样例
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;
}