深搜,只不过是三维的。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<algorithm> 5 using namespace std; 6 int l,r,c; 7 int sx,sy,sz; 8 int ex,ey,ez; 9 int ans=99999; 10 char map[41][41][41]; 11 int book[41][41][41]= {0}; 12 int flag=0; 13 void dfs(int x,int y,int z,int step) { 14 if(x==ex&&y==ey&&z==ez) { 15 ans=min(ans,step); 16 flag=1; 17 return; 18 } 19 if(map[x+1][y][z]!='#'&&book[x+1][y][z]!=1&&x+1<=l) { 20 book[x+1][y][z]=1; 21 dfs(x+1,y,z,step+1); 22 book[x+1][y][z]=0; 23 } 24 if(map[x-1][y][z]!='#'&&book[x-1][y][z]!=1&&x-1>=1) { 25 book[x-1][y][z]=1; 26 dfs(x-1,y,z,step+1); 27 book[x-1][y][z]=0; 28 } 29 if(map[x][y+1][z]!='#'&&book[x][y+1][z]!=1&&y+1<=r) { 30 book[x][y+1][z]=1; 31 dfs(x,y+1,z,step+1); 32 book[x][y+1][z]=0; 33 } 34 if(map[x][y-1][z]!='#'&&book[x][y-1][z]!=1&&y-1>=1) { 35 book[x][y-1][z]=1; 36 dfs(x,y-1,z,step+1); 37 book[x][y-1][z]=0; 38 } 39 if(map[x][y][z+1]!='#'&&book[x][y][z+1]!=1&&z+1<=c) { 40 book[x][y][z+1]=1; 41 dfs(x,y,z+1,step+1); 42 book[x][y][z+1]=0; 43 } 44 if(map[x][y][z-1]!='#'&&book[x][y][z-1]!=1&&z-1>=1) { 45 book[x][y][z-1]=1; 46 dfs(x,y,z-1,step+1); 47 book[x][y][z-1]=0; 48 } 49 } 50 int main() { 51 while((cin>>l>>r>>c)&&l!=0&&r!=0&&c!=0) { 52 for(int i=1; i<=l; i++) { 53 for(int j=1; j<=r; j++) { 54 for(int k=1; k<=c; k++) { 55 cin>>map[i][j][k]; 56 if(map[i][j][k]=='S') { 57 sx=i; 58 sy=j; 59 sz=k; 60 book[i][j][k]=1; 61 } 62 if(map[i][j][k]=='E') { 63 ex=i; 64 ey=j; 65 ez=k; 66 } 67 } 68 } 69 } 70 dfs(sx,sy,sz,0); 71 if(flag==0) { 72 cout<<"Trapped!"<<endl; 73 } 74 else 75 { 76 cout<<"Escaped in "<<ans<<" minute(s)."<<endl; 77 } 78 memset(book,0,sizeof(book)); 79 flag=0; 80 ans=99999; 81 } 82 }
请各位大佬斧正(反正我不认识斧正是什么意思)