题目:http://acm.hdu.edu.cn/showproblem.php?pid=2102
1 5 5 14 S*#*. .#... ..... ****. ...#. ..*.P #.*.. ***.. ...*. *.#..
YES
#include <iostream> #include <cstdio> #include<cstring> #include<queue> using namespace std; char s[2][15][15]; bool vis[2][15][15]; int n,m,t; int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}}; int change(int a){ if(a==0)return 1; else return 0; } typedef struct node{ int x,y,z,step; }Node; int bfs(){ queue<Node> que; Node temp; temp.step=0; temp.x=temp.y=temp.z=0; que.push(temp); while(!que.empty()){ temp=que.front(); que.pop(); int xx=temp.x,yy=temp.y,zz=temp.z; if(s[zz][xx][yy]=='P'){ return temp.step; } for(int i=0;i<4;i++){ int tx=xx+dir[i][0],ty=yy+dir[i][1],tz=zz; if(tx<0||tx>=n||ty<0||ty>=m||s[tz][tx][ty]=='*')continue; if(s[tz][tx][ty]=='#'&&!vis[tz][tx][ty]){ vis[tz][tx][ty]=1; tz=change(tz); if(s[tz][tx][ty]=='#'|| s[tz][tx][ty]=='*'){ tz=change(tz); s[tz][tx][ty]='*'; continue ; } Node tmp; tmp.step=temp.step+1; tmp.x=tx; tmp.y=ty; tmp.z=tz; vis[tz][tx][ty]=1; que.push(tmp); } else if(s[tz][tx][ty]=='.'&&!vis[tz][tx][ty]){ vis[tz][tx][ty]=1; Node tmp; tmp.step=temp.step+1; if(tmp.step>t)continue; tmp.x=tx; tmp.y=ty; tmp.z=tz; que.push(tmp); } else if(s[tz][tx][ty]=='P'){ if(temp.step+1>t)continue; return temp.step+1; } } } return -1; } int main() { //freopen("cin.txt","r",stdin); int ca; cin>>ca; while(ca--){ scanf("%d%d%d",&n,&m,&t); memset(s,0,sizeof(s)); for(int k=0;k<2;k++) for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>s[k][i][j]; } } s[0][0][0]='*'; memset(vis,0,sizeof(vis)); vis[0][0][0]=1; int mytime=bfs(); if(mytime!=-1&&mytime<=t)printf("YES\n"); else printf("NO\n"); } return 0; }原来误导版的T时刻到达(果断TLE):
#include <iostream> #include <cstdio> using namespace std; char s[2][15][15]; int n,m,t; int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}}; bool flag; int change(int a){ if(a==0)return 1; else return 0; } void dfs(int x,int y,int dex,int mytime){ if(flag==1||mytime>t)return ; for(int i=0;i<4;i++){ int tx=x+dir[i][0],ty=y+dir[i][1]; if(tx<0||tx>=n||ty<0||ty>=m)continue; if(s[dex][tx][ty]=='P'&&mytime==t){ flag=1; return ; } else if(s[dex][tx][ty]=='*'){ continue ; } else if(s[dex][tx][ty]=='.'){ s[dex][tx][ty]='*'; dfs(tx,ty,dex,mytime+1); s[dex][tx][ty]='.'; } else if(s[dex][tx][ty]=='#'){ s[dex][tx][ty]='*'; dex=change(dex); dfs(tx,ty,dex,mytime); dex=change(dex); s[dex][tx][ty]='#'; } } } int main() { //freopen("cin.txt","r",stdin); int ca; cin>>ca; while(ca--){ scanf("%d%d%d",&n,&m,&t); for(int k=0;k<2;k++) for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>s[k][i][j]; } } flag=0; s[0][0][0]='*'; dfs(0,0,0,0); if(flag)printf("YES\n"); else printf("NO\n"); } return 0; }