题意:
一个8 * 8 的棋盘上面有四个棋子
棋子可以上下左右移动,如果隔壁有个棋子 那就可以跳一步,只能跳一步。
给出 初始状态,和末尾状态 求能不能在8步之内达到
思路:双向bfs
状态压缩,整个棋盘压缩为64位的long long
正向走4层,反向走4层,看是否有交点。
参考:https://blog.csdn.net/cacyth/article/details/48572945
#include <cstdio>
#include <set>
#include <queue>
#include <cstring>
#include <algorithm>
#define fi first
#define se second
#define pii pair<int,int>
using namespace std;
typedef long long LL;
const int maxn = 1e3+5;
int moved[4][2] = {{1,0}, {0,-1}, {-1,0}, {0,1}};
set<LL> s1, s2;
queue<LL> Q;
// 输入点,并将二维转化为一维
void input(LL &a){
int x,y;
scanf("%d%d",&x,&y);
--x; --y;
int z = x*8 + y;
a |= (1LL << z);
}
// 检查点是否在棋盘内
bool check(int x, int y){
if(x >= 0&&x < 8&&y >= 0&&y < 8) return true;
return false;
}
// 清空队列
void clear_que(queue<LL> &Q){
queue<LL> empty;
swap(Q, empty);
}
// 当前棋盘s, 扩展层数cnt,从起点开始扩展过(正向bfs)的点s1,从终点扩展过的点(反向bfs)的点s2,sec:是否是第二次bfs(反向bfs)
// 返回是否找到交点
bool expand(LL s, int &next_layer, set<LL> &ss1, set<LL> &ss2, bool sec){
// 根据s找到4个点
bool exists[10][10]; //棋盘上(x,y)是否是点
memset(exists, 0, sizeof(exists));
int P[5][2]; // 记录棋盘上的4个点
int cnt = 0;
for(int i = 0; i < 64; ++i){
if(s&(1LL << i)){ //找到一个点
int x = i/8;
int y = i%8;
exists[x][y] = 1;
P[cnt][0] = x;
P[cnt++][1] = y;
}
}
// 依次扩展
for(int i = 0; i < 4; ++i){
int x = P[i][0], y = P[i][1];
int z = x*8 + y;
LL t = s - (1LL << z);
LL next_state;
for(int j = 0; j < 4; ++j){ // 4个方向
next_state = t;
int x2 = x + moved[j][0];
int y2 = y + moved[j][1];
if(check(x2, y2)&&exists[x2][y2]){ //有邻居,可以跳一格
x2+= moved[j][0];
y2+= moved[j][1];
}
if(!check(x2,y2)||exists[x2][y2]) continue; //若该位置不在棋盘或已经有棋子
z = x2*8 + y2;
next_state += (1LL << z);
if(!ss1.count(next_state)){
if(sec && ss2.count(next_state)) return true; // 如果是反向搜索且有交点了,找到解
Q.push(next_state);
//if(sec) printf("22222: ");
//else printf("111111: ");
//printf("%d,%d\n", x2+1,y2+1);
//printf("%lld\n",next_state);
ss1.insert(next_state);
++next_layer;
}
}
}
return false;
}
bool bfs(LL s, set<LL> &ss1, set<LL> &ss2, bool sec){
clear_que(Q);
Q.push(s);
ss1.clear();
ss1.insert(s);
int cnt = 0; // 当前扩展层数
int next_layer; // 下一层点的个数
int cur_layer = 1; //当前层中点的个数
while(cnt < 4){
next_layer = 0;
while(cur_layer > 0){
LL t = Q.front(); Q.pop(); --cur_layer;
bool ans = expand(t, next_layer, ss1, ss2, sec);
if(ans) return true;
}
//printf("next is %d\n",next_layer);
cur_layer = next_layer;
//printf("cur id %d\n",cur_layer);
++cnt;
}
return false;
}
bool solve(LL s, LL e){ //这里写的int导致一直错,太不小心了
bfs(s, s1, s2, false); // 正向搜
return bfs(e, s2, s1, true); // 反向搜
}
int main()
{
//freopen("in.txt","r",stdin);
int x,y;
LL s,e;
while(scanf("%d%d",&x,&y) == 2){
s = e = 0;
--x; --y;
int z = x*8 + y; //二维变一维
s |= (1LL << z);
for(int i = 1; i < 4; ++i) input(s);
for(int i = 0; i < 4; ++i) input(e);
//printf("input ok");
bool ans = solve(s, e);
if(ans) printf("YES\n");
else printf("NO\n");
}
return 0;
}