hdoj 1254 推箱子 bfs中套bfs
题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1254
一个bfs()搜索箱子走的位置。。还一个bfs()搜索人不是能到推箱子的地方。考虑因素比较多
1:人不能通过箱子的地方
2:人走到的地方不能是墙
3:箱子不能推到墙
4:地图是一直在变的当箱子被推。原来的位置就变成空地
还需要注意一个位置能有四个方向推入。。而四个位置推入导致的结果可能不同。所以标记是否走过时数组在开一维表示推入方向。
献上ac代码
1 #include<stdio.h> 2 #include<algorithm> 3 #include<queue> 4 #include<conio.h> 5 using namespace std; 6 #define map mapp 7 8 int mapp[10][10]; 9 int vis[10][10][5], vis1[10][10]; 10 int pe_sx, pe_sy, b_sx, b_sy, n, m, b_ex,b_ey; 11 int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; 12 13 struct st 14 { 15 int x; 16 int y; 17 int xx; 18 int yy; 19 int time; 20 }next,u; 21 22 struct stt 23 { 24 int x; 25 int y; 26 }te,tee; 27 28 int check(int start_x,int start_y,int end_x,int end_y,int mapp[10][10]) 29 { 30 31 32 memset(vis1,0,sizeof(vis1)); 33 queue<stt>q; 34 te.x=start_x,te.y=start_y; 35 vis1[start_x][start_y]=1; 36 q.push(te); 37 while(!q.empty()) 38 { 39 int i; 40 tee=q.front(); 41 q.pop(); 42 if(tee.x==end_x&&tee.y==end_y) 43 return 1; 44 for(i=0;i<=3;i++) 45 { 46 int temp_x=tee.x+dx[i]; 47 int temp_y=tee.y+dy[i]; 48 49 50 51 if(!vis1[temp_x][temp_y]&&mapp[temp_x][temp_y]!=1&&mapp[temp_x][temp_y]!=2) 52 { 53 te.x=temp_x,te.y=temp_y; 54 vis1[temp_x][temp_y]=1; 55 if(temp_x==end_x&&temp_y==end_y) 56 return 1; 57 q.push(te); 58 } 59 } 60 } 61 return 0; 62 } 63 int bfs() 64 { 65 memset(vis,0,sizeof(vis)); 66 queue<st>q; 67 u.x=pe_sx,u.y=pe_sy,u.time=0,u.xx=b_sx,u.yy=b_sy; 68 q.push(u); 69 while(!q.empty()) 70 { 71 int i, j; 72 u=q.front(); 73 q.pop(); 74 int t_map[10][10]; 75 for(i=0;i<=n+1;i++) 76 { 77 for(j=0;j<=m+1;j++) 78 { 79 t_map[i][j]=mapp[i][j]; 80 } 81 82 } 83 t_map[pe_sx][pe_sy]=0,t_map[b_sx][b_sy]=0; 84 t_map[u.x][u.y]=4,t_map[u.xx][u.yy]=2; 85 86 for(i=0;i<=3;i++) 87 { 88 int temp_x = u.xx+dx[i]; 89 int temp_y = u.yy+dy[i]; 90 91 if(vis[temp_x][temp_y][i]||t_map[temp_x][temp_y]==1||t_map[u.xx-dx[i]][u.yy-dy[i]]==1) 92 continue; 93 //printf("%d %d %d %d %d\n",u.x,u.y,u.xx-dx[i],u.yy-dy[i],check(u.x,u.y,u.xx-dx[i],u.yy-dy[i],t_map)); 94 if(check(u.x,u.y,u.xx-dx[i],u.yy-dy[i],t_map)) 95 { 96 97 next.x=u.xx,next.y=u.yy,next.xx=temp_x,next.yy=temp_y; 98 next.time=u.time+1; 99 //printf("%d %d %d %d\n",u.x,u.y,u.xx-dx[i],u.yy-dy[i]); 100 vis[temp_x][temp_y][i]=1; 101 if(temp_x==b_ex&&temp_y==b_ey) 102 return next.time; 103 q.push(next); 104 } 105 } 106 } 107 return -1; 108 } 109 110 int main() 111 { 112 int t; 113 scanf("%d",&t); 114 while(t--) 115 { 116 int i, j; 117 scanf("%d %d",&n,&m); 118 for(i=0;i<=8;i++) 119 { 120 for(j=0;j<=8;j++) 121 mapp[i][j]=1; 122 } 123 for(i=1;i<=n;i++) 124 { 125 for(j=1;j<=m;j++) 126 { 127 scanf("%d",&mapp[i][j]); 128 if(mapp[i][j]==4) 129 pe_sx=i,pe_sy=j; 130 else if(mapp[i][j]==2) 131 b_sx=i,b_sy=j; 132 else if(mapp[i][j]==3) 133 b_ex=i,b_ey=j; 134 } 135 } 136 printf("%d\n",bfs()); 137 } 138 return 0; 139 }