您的位置:首页 > 其它

HDU3309Roll The Cube( = = BFS )

2015-08-07 16:48 337 查看
题意:同时控制俩个球,把他们移动到洞里

当两个球重合时,只要一个球在洞里,那么另一个求解可以从这里经过,两球是同时运动的

#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
#include<set>
#include<stack>
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define out(x) cout<<x<<endl;
using namespace std;
const int maxn=25;
const int inf=9999999;
int n,m;
char a[maxn][maxn];
bool vis[maxn][maxn][maxn][maxn];
int dir[][2]={{0,1},{1,0},{-1,0},{0,-1}};
bool pan(P s){
if(s.X<0||s.X>=n||s.Y<0||s.Y>=m||a[s.X][s.Y]=='*')return false;
return true;
}
struct node{
int x[2],y[2],step;
};

node st;
int bfs(){
queue<node> q;
cl(vis,false);
st.step=0;
q.push(st);
vis[st.x[0]][st.y[0]][st.x[1]][st.y[1]]=true;

while(!q.empty()){

node zcc=q.front();q.pop();
// printf("===%d\n",zcc.step);
int flag=0;
for(int i=0;i<4;i++){
node s=zcc;

if(a[s.x[0]][s.y[0]]=='H'){//有一个球进洞
flag=1;
}
else {
s.x[0]+=dir[i][0];
s.y[0]+=dir[i][1];
}
if(!pan(P(s.x[0],s.y[0]))){
s.x[0]-=dir[i][0];
s.y[0]-=dir[i][1];
}

if(a[s.x[1]][s.y[1]]!='H'||flag){//如果当前不是在洞口,或者另一个球进洞了,那么这个球不受限制了,自由的在图中移动
s.x[1]+=dir[i][0];
s.y[1]+=dir[i][1];
}
if(!pan(P(s.x[1],s.y[1]))){
s.x[1]-=dir[i][0];
s.y[1]-=dir[i][1];
}
if(vis[s.x[0]][s.y[0]][s.x[1]][s.y[1]])continue;
if(s.x[0]==s.x[1]&&s.y[0]==s.y[1]){
if(a[s.x[0]][s.y[0]]=='H'||a[s.x[1]][s.y[1]]=='H'){
vis[s.x[0]][s.y[0]][s.x[1]][s.y[1]]=true;

s.step++;
q.push(s);
}
}
else {
if(a[s.x[0]][s.y[0]]=='H'&&a[s.x[1]][s.y[1]]=='H'){
return s.step+1;
}
vis[s.x[0]][s.y[0]][s.x[1]][s.y[1]]=true;

s.step++;
q.push(s);
}
}
}
return -1;
}

int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
bool first=true;
for(int i=0;i<n;i++){
scanf("%s",a[i]);
for(int j=0;j<m;j++)if(a[i][j]=='B'){
if(first){
st.x[0]=i;st.y[0]=j;
first=false;
a[i][j]='.';
}
else {
st.x[1]=i;
st.y[1]=j;
a[i][j]='.';
}
}
}

int ans=bfs();
if(ans==-1){
puts("Sorry , sir , my poor program fails to get an answer.");
}
else {
printf("%d\n",ans);
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: