HDU 1732 BFS

来源:互联网 发布:聊天室源码下载 编辑:程序博客网 时间:2024/05/14 01:59

推箱子升级版

一共只有三个箱子,8*8矩阵,BFS水之


#include "iostream"#include "algorithm"#include "queue"using namespace std;struct node{int x[4],y[4];int step;}cur,next;queue<node>q;int dir[4][2]={1,0,-1,0,0,1,0,-1};bool hash[8][8][8][8][8][8][8][8]; // hash判重,记录包括人和箱子的位置int ans,n,m;int f[10][10];// 记录目标位置char map[10][10];void bfs(){int i,j,xx,yy,x,y;while (!q.empty()){cur=q.front();q.pop();if (f[cur.x[1]][cur.y[1]]==1 && f[cur.x[2]][cur.y[2]]==1 && f[cur.x[3]][cur.y[3]]==1) { ans=cur.step; return ;}for (i=0;i<4;i++){x=cur.x[0]+dir[i][0]; xx=x+dir[i][0];y=cur.y[0]+dir[i][1]; yy=y+dir[i][1];if (x<0 || x>=n || y<0 || y>=m || map[x][y]=='#') continue;if (!((x==cur.x[1] && y==cur.y[1]) || (x==cur.x[2] && y==cur.y[2]) || (x==cur.x[3] && y==cur.y[3])) ) // 新位置为空{if (hash[x] [y] [cur.x[1]] [cur.y[1]] [cur.x[2]] [cur.y[2]] [cur.x[3]] [cur.y[3]]==0) continue;hash[x] [y] [cur.x[1]] [cur.y[1]] [cur.x[2]] [cur.y[2]] [cur.x[3]] [cur.y[3]]=0;next=cur;next.x[0]=x;next.y[0]=y;next.step++;q.push(next);}else if ( xx>=0 && xx<n && yy>=0 && yy<m && map[xx][yy]!='#') {if(!((xx==cur.x[1] && yy==cur.y[1]) || (xx==cur.x[2] && yy==cur.y[2]) || (xx==cur.x[3] && yy==cur.y[3])) ) // 新位置为箱子{next=cur;next.step++;next.x[0]=x; next.y[0]=y;if (x==cur.x[1] && y==cur.y[1]){next.x[1]=xx;next.y[1]=yy;}if (x==cur.x[2] && y==cur.y[2]){next.x[2]=xx;next.y[2]=yy;}if (x==cur.x[3] && y==cur.y[3]){next.x[3]=xx;next.y[3]=yy;}if (hash[x] [y] [next.x[1]] [next.y[1]] [next.x[2]] [next.y[2]] [next.x[3]] [next.y[3]]==0) continue;hash[x] [y] [next.x[1]] [next.y[1]] [next.x[2]] [next.y[2]] [next.x[3]] [next.y[3]]=0;q.push(next);}}}}}int main(){int w,i,j;while (scanf("%d%d",&n,&m)!=EOF){memset(hash,true,sizeof(hash));memset(f,0,sizeof(f));while (!q.empty()) q.pop();getchar();w=0;for (i=0;i<n;i++){scanf("%s",map[i]);for (j=0;j<m;j++){if (map[i][j]=='*'){w++;cur.x[w]=i;cur.y[w]=j;map[i][j]='.';}if (map[i][j]=='X'){cur.x[0]=i;cur.y[0]=j;map[i][j]='.';}if (map[i][j]=='@'){f[i][j]=1;map[i][j]='.';}}}hash[cur.x[0]] [cur.y[0]] [cur.x[1]] [cur.y[1]] [cur.x[2]] [cur.y[2]] [cur.x[3]] [cur.y[3]]=0;cur.step=0;q.push(cur);ans=-1;bfs();printf("%d\n",ans);}return 0;}



0 0