题目:LINK
模拟搜索题目BFS,给定的图不大22*22,关键是如何记录搜索过的状态,开5维[x1][y1][x2][y2][4],分别表示两个球x1, y1, x2, y2坐标,4表示两个洞(因为两洞坐标不变)的存在状态00表示都被填01表示第一个被填10表示第二个被填,11表示都存在
注意,两球虽然同时运动,但一个球遇到障碍物,另一个球可能可以运动,但是如果被挡不能运动的球的坐标和另一个球运动后的坐标相同,那么另一个球也不能运动。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
using namespace std;
#define INF 1000000000
#define N 24
int t, n, m, vis[N][N][N][N][4], hx1, hy1, hx2, hy2;
char mm[N][N];
struct node
{
int x1, x2, y1, y2, sta, step;
};
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
node S;
void test(node &in, int ax, int ay)
{
int x1, y1, x2, y2;
x1 = in.x1 + ax;
y1 = in.y1 + ay;
x2 = in.x2 + ax;
y2 = in.y2 + ay;
int flag1, flag2;
flag1 = flag2= 0;
if(in.x1 != 0 && in.y1 != 0 && in.x2 != 0 && in.y2 !=0) {
if(x1 < 1 || x1 > n || y1 <1 || y1 > m) flag1 = 1;
else {
if(mm[x1][y1] == '*') flag1 = 1;
}
if(x2 < 1 || x2 > n || y1 < 1 || y2 > m) flag2 = 1;
else {
if(mm[x2][y2] == '*') flag2= 1;
}
if(flag1 && flag2 == 0 && x2 == in.x1 && y2 == in.y1) flag2 = 1;
if(flag1 == 0 && flag2 && x1 == in.x2 && y1 == in.y2) flag1 = 1;
if(!flag1) in.x1 = x1, in.y1 = y1;
if(!flag2) in.x2 = x2, in.y2 = y2;
}
else {
if(in.x1!=0 && in.y1 != 0) {
if(x1 < 1 || x1 > n || y1 <1 || y1 > m) flag1 = 1;
else {
if(mm[x1][y1] == '*') flag1 = 1;
}
if(!flag1) in.x1 = x1, in.y1 = y1;
}
if(in.x2 != 0 && in.y2 != 0) {
if(x2 < 1 || x2 > n || y2 < 1 || y2 > m) flag2 = 1;
else {
if(mm[x2][y2] == '*') flag2= 1;
}
if(!flag2) in.x2 = x2, in.y2 = y2;
}
}
}
int bfs()
{
queue< node > Q;
memset(vis, 0, sizeof(vis));
S.sta = 3; S.step = 0;
Q.push(S);
vis[S.x1][S.y1][S.x2][S.y2][S.sta] = 1;
node now, next, tmp;
while(!Q.empty()) {
now = Q.front(); Q.pop();
if(now.sta == 0) return now.step;
for(int i=0; i<4; i++) {
tmp = now;
test(tmp, dir[i][0], dir[i][1]);
tmp.step = now.step + 1;
if(tmp.sta & 1) {
if(tmp.x1 == hx1 && tmp.y1 == hy1) {
tmp.x1 = 0; tmp.y1 = 0; tmp.sta &= 2;
}
if(tmp.x2 == hx1 && tmp.y2 == hy1) {
tmp.x2 = 0; tmp.y2 = 0; tmp.sta &= 2;
}
}
if(tmp.sta & 2) {
if(tmp.x1 == hx2 && tmp.y1 == hy2) {
tmp.x1 = 0; tmp.y1 = 0; tmp.sta &= 1;
}
if(tmp.x2 == hx2 && tmp.y2 == hy2) {
tmp.x2 = 0; tmp.y2 = 0; tmp.sta &= 1;
}
}
if(vis[tmp.x1][tmp.y1][tmp.x2][tmp.y2][tmp.sta]) continue;
vis[tmp.x1][tmp.y1][tmp.x2][tmp.y2][tmp.sta] = 1;
Q.push(tmp);
}
}
return -1;
}
int main()
{
scanf("%d", &t);
while( t-- ) {
scanf("%d%d", &n, &m);
int sumb=0, sumh = 0;
for(int i=1; i<=n; i++) {
scanf("%s", mm[i]+1);
for(int j = 1; j <= m; j++) {
if(mm[i][j] == 'B') {
mm[i][j] = '.';
if(sumb == 0) {
sumb ++; S.x1 = i; S.y1 = j;
}
else {
S.x2= i; S.y2 = j;
}
}
else if(mm[i][j] == 'H') {
if(sumh == 0) {
sumh ++;
hx1 = i; hy1 = j;
}
else {
hx2 = i; hy2 = j;
}
}
}
}
int ans = bfs() ;
if(ans<0) printf("Sorry , sir , my poor program fails to get an answer.\n");
else printf("%d\n", ans);
}
return 0;
}