您的位置:首页 > 其它

bfs+bfs/dfs hdu 1254 推箱子1

2012-02-25 17:22 302 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1254

推箱子

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
/*
BFS+BFS/DFS,第二个用于判断是否能移动到可以推得位置,因为矩阵很小所以就
DFS也不担心 TLE了,
注意第二组数据,箱子路径可能会重复,所以标记vis要开思维同时记录箱子和人的
位置
*/
using namespace std;
int maze[7][7],move[][2]={0,1,1,0,0,-1,-1,0},dex,dey;
int dvis[7][7];
int m,n;
struct node
{
int px,py,bx,by;
}p;

bool ok(int x,int y)
{
if(x<0||x>=m||y<0||y>=n||maze[x][y]==1)
return 0;
return 1;
}
bool connect(int bx,int by, int dx, int dy)
{
if(bx==dx&&by==dy)
return 1;
int x,y;
for(int i=0;i<4;++i)
{
x=bx+move[i][0];
y=by+move[i][1];
if(ok(x,y)&&!dvis[x][y])
{
dvis[x][y]=1;
if(connect(x,y,dx,dy))
return 1;
dvis[x][y]=0;
}
}
return 0;
}
int bfs()
{
int vis[7][7][7][7]={0};
vis[p.bx][p.by][p.px][p.py]=1;
node t;
int x,y;
queue<node>  que;
que.push(p);
while(!que.empty())
{
p=que.front();
que.pop();
for(int i=0;i<4;++i)
{
t.bx=p.bx+move[i][0];
t.by=p.by+move[i][1];
t.px=p.bx;
t.py=p.by;
x=p.bx+move[(i+2)%4][0];
y=p.by+move[(i+2)%4][1];
if(ok(t.bx,t.by)&&ok(x,y)&&!vis[t.bx][t.by][t.px][t.py])
{
memset(dvis,0,sizeof(dvis));
dvis[x][y]=1;
maze[p.bx][p.by]=1;
if(connect(x,y,p.px,p.py))
{
if(t.bx==dex&&t.by==dey)
return vis[p.bx][p.by][p.px][p.py];
vis[t.bx][t.by][t.px][t.py]=vis[p.bx][p.by][p.px][p.py]+1;
que.push(t);
}
maze[p.bx][p.by]=0;
}
}
}
return -1;
}
int main()
{

int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
{
scanf("%d",&maze[i][j]);
if(maze[i][j]==2)
{
p.bx=i;
p.by=j;
maze[i][j]=0;
}
else if(maze[i][j]==4)
{
p.px=i;
p.py=j;
maze[i][j]=0;
}
else if(maze[i][j]==3)
{
dex=i;
dey=j;
maze[i][j]=0;
}
}
printf("%d\n",bfs());
}
return  0;
}
/*
2
5 5
0 3 0 0 0
1 0 1 4 0
0 0 1 0 0
1 0 2 0 0
0 0 0 0 0

5 5
0 4 0 0 0
1 2 1 0 0
3 0 0 1 0
1 0 0 1 0
1 0 0 1 0

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