Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
比较简单的bfs...一次acstruct里存box的左上角坐标、方向、时间 hash可以利用位运算来做 #include"iostream" #include"cstdlib" #include"queue" #include"cstdio" #include"string.h" using namespace std; int R,C; char map[501][501]; short used[501][501]; struct node{ int d,x,y,t; node(int d,int x,int y,int t):d(d),x(x),y(y),t(t){} }; int data[4]={1,2,4,8}; queue<node>q; int bfs(int sx,int sy,int sd){ int x,y,d,ti; while(!q.empty())q.pop(); memset(used,0,sizeof(used)); node t(sd,sx,sy,0); q.push(t); used[sx][sy]=data[sd]; while(!q.empty()){ t=q.front(); q.pop(); x=t.x; y=t.y; d=t.d; ti=t.t; if(d==0){ if(map[x-1][y]!='#' && map[x-2][y]!='#'){ if((used[x-2][y]&4)==0){ used[x-2][y]|=4; q.push(node(2,x-2,y,ti+1)); } } if(map[x+1][y]!='#' && map[x+2][y]!='#'){ if((used[x+1][y]&4)==0){ used[x+1][y]|=4; q.push(node(2,x+1,y,ti+1)); } } if(map[x][y-1]!='#' && map[x][y-2]!='#'){ if((used[x][y-2]&2)==0){ used[x][y-2]|=2; q.push(node(1,x,y-2,ti+1)); } } if(map[x][y+1]!='#' && map[x][y+2]!='#'){ if((used[x][y+1]&2)==0){ used[x][y+1]|=2; q.push(node(1,x,y+1,ti+1)); } } } else if(d==1){ if(map[x-1][y]!='#' && map[x-1][y+1]!='#'){ if((used[x-1][y]&2)==0){ used[x-1][y]|=2; q.push(node(1,x-1,y,ti+1)); } } if(map[x+1][y]!='#' && map[x+1][y+1]!='#'){ if((used[x+1][y]&2)==0){ used[x+1][y]|=2; q.push(node(1,x+1,y,ti+1)); } } if(map[x][y-1]!='#' && map[x][y-1]!='E'){ if(map[x][y-1]=='O')return ti+1; if((used[x][y-1]&1)==0){ used[x][y-1]|=1; q.push(node(0,x,y-1,ti+1)); } } if(map[x][y+2]!='#' && map[x][y+2]!='E'){ if(map[x][y+2]=='O')return ti+1; if((used[x][y+2]&1)==0){ used[x][y+2]|=1; q.push(node(0,x,y+2,ti+1)); } } } else if(d==2){ if(map[x-1][y]!='#' && map[x-1][y]!='E'){ if(map[x-1][y]=='O')return ti+1; if((used[x-1][y]&1)==0){ used[x-1][y]|=1; q.push(node(0,x-1,y,ti+1)); } } if(map[x+2][y]!='#' && map[x+2][y]!='E'){ if(map[x+2][y]=='O')return ti+1; if((used[x+2][y]&1)==0){ used[x+2][y]|=1; q.push(node(0,x+2,y,ti+1)); } } if(map[x][y-1]!='#' && map[x+1][y-1]!='#'){ if((used[x][y-1]&4)==0){ used[x][y-1]|=4; q.push(node(2,x,y-1,ti+1)); } } if(map[x][y+1]!='#' && map[x+1][y+1]!='#'){ if((used[x][y+1]&4)==0){ used[x][y+1]|=4; q.push(node(2,x,y+1,ti+1)); } } } } return -1; } int main(){ int x0,y0,d0,res; bool flag; while(scanf("%d%d",&R,&C)&&R){ for(int i=0;i<R;i++){ scanf(" %s",map[i]); } flag=false; for(int i=1;i<R-1;i++){ for(int j=1;j<C-1;j++){ if(map[i][j]=='X'){ x0=i; y0=j; if(map[i][j+1]=='X')d0=1; else if(map[i+1][j]=='X')d0=2; else d0=0; flag=true; break; } } if(flag)break; } res=bfs(x0,y0,d0); if(res==-1)printf("Impossible\n"); else printf("%d\n",res); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator