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 */
相关文章推荐
- HDU 1254 - 推箱子(BFS + DFS)
- HDU 1254 推箱子(BFS + DFS)
- 【BFS+DFS】hdu 1254 推箱子
- hdu 1254 推箱子(嵌套搜索,bfs中有dfs)
- hdu 1254 推箱子 (bfs+dfs+预处理)
- hdu 1254 推箱子(BFS+BFS或BFS+DFS)
- 【HDU】1254 推箱子(BFS DFS HASH记录走过的状态)
- HDU 1254 推箱子 (BFS + DFS)
- HDU 1254 推箱子 (搜索中套搜索,BFS + DFS 这感觉,酸爽!)
- HDU 1254:推箱子【DFS && BFS】
- HDU1254--推箱子(BFS+DFS)
- HDU 1254推箱子(bfs+dfs)
- HDU 1254 推箱子(双层BFS)
- hdoj 1254 推箱子 【BFS+DFS】
- hdu1254 推箱子--BFS
- hdu 1254 推箱子 很好的嵌套搜索 双层BFS
- HDU - 1254 推箱子【bfs+bfs】
- hdu 1254(推箱子游戏bfs+状态标记)
- HDU 1254 推箱子(双重bfs)
- 题解: HDU 1254 :推箱子 (BFS)