题意:三维迷宫,求逃出去的最短时间
题解:用DFS最佳,注意vis存储最短距离
1 #include<iostream>
2 #include<cstdio>
3 #include<algorithm>
4 #include<climits>
5 #include<cstring>
6 using namespace std;
7 bool map[102][102][102];
8 int vis[102][102][102];
9 void dfs(int z,int x,int y)
10 {
11 if(vis[z-1][x][y]>vis[z][x][y]+1&&map[z-1][x][y])
12 {
13 vis[z-1][x][y]=vis[z][x][y]+1;
14 dfs(z-1,x,y);
15 }
16 if(vis[z+1][x][y]>vis[z][x][y]+1&&map[z+1][x][y])
17 {
18 vis[z+1][x][y]=vis[z][x][y]+1;
19 dfs(z+1,x,y);
20 }
21 if(vis[z][x-1][y]>vis[z][x][y]+1&&map[z][x-1][y])
22 {
23 vis[z][x-1][y]=vis[z][x][y]+1;
24 dfs(z,x-1,y);
25 }
26 if(vis[z][x+1][y]>vis[z][x][y]+1&&map[z][x+1][y])
27 {
28 vis[z][x+1][y]=vis[z][x][y]+1;
29 dfs(z,x+1,y);
30 }
31 if(vis[z][x][y-1]>vis[z][x][y]+1&&map[z][x][y-1])
32 {
33 vis[z][x][y-1]=vis[z][x][y]+1;
34 dfs(z,x,y-1);
35 }
36 if(vis[z][x][y+1]>vis[z][x][y]+1&&map[z][x][y+1])
37 {
38 vis[z][x][y+1]=vis[z][x][y]+1;
39 dfs(z,x,y+1);
40 }
41 return;
42 }
43 int main()
44 {
45 int l,n,m;
46 while(true)
47 {
48 scanf("%d%d%d",&l,&n,&m);
49 if(l==0&&n==0&&m==0)
50 {
51 break;
52 }
53 memset(map,false,sizeof(map));
54 for(int i=1;i<=l;i++)
55 {
56 for(int j=1;j<=n;j++)
57 {
58 for(int k=1;k<=m;k++)
59 {
60 vis[i][j][k]=INT_MAX;
61 }
62 }
63 }
64 getchar();
65 int s_x;
66 int s_y;
67 int s_z;
68 int e_x;
69 int e_y;
70 int e_z;
71 for(int i=1;i<=l;i++)
72 {
73 for(int j=1;j<=n;j++)
74 {
75 for(int k=1;k<=m;k++)
76 {
77 char c=getchar();
78 if(c=='S')
79 {
80 s_x=j;
81 s_y=k;
82 s_z=i;
83 map[i][j][k]=true;
84 }
85 if(c=='E')
86 {
87 e_x=j;
88 e_y=k;
89 e_z=i;
90 map[i][j][k]=true;
91 }
92 if(c=='#')
93 {
94 map[i][j][k]=false;
95 }
96 if(c=='.')
97 {
98 map[i][j][k]=true;
99 }
100 }
101 getchar();
102 }
103 getchar();
104 }
105 vis[s_z][s_x][s_y]=0;
106 dfs(s_z,s_x,s_y);
107 if(vis[e_z][e_x][e_y]!=INT_MAX)
108 {
109 printf("Escaped in %d minute(s).\n",vis[e_z][e_x][e_y]);
110 }
111 else
112 {
113 printf("Trapped!\n");
114 }
115 }
116 return 0;
117 }