错了三次
第一次写成了DFS 超时了
第二次没意识到问题的关键所在 在DFS的基础上去掉了一行 WA了
第三次用了BFS 但是MLE了 代码如下
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 99999
using namespace std;
char m[35][35][35];
int L,R,C;
struct coor
{
int a,b,d;
int ans;
}s;
int bfs()
{
queue<coor>q;
s.ans = 0;
q.push(s);
while(!q.empty()){
coor now = q.front();
int l = now.a;
int r = now.b;
int c = now.d;
q.pop();
if(m[l][r][c]=='E') return now.ans;
m[l][r][c]='#';
coor next;
if(m[l+1][r][c]=='.'||m[l+1][r][c]=='E'){
next.a = l+1;
next.b = r;
next.d = c;
next.ans = now.ans+1;
q.push(next);
}
if(m[l][r+1][c]=='.'||m[l][r+1][c]=='E'){
next.a = l;
next.b = r+1;
next.d = c;
next.ans = now.ans+1;
q.push(next);
}
if(m[l][r][c+1]=='.'||m[l][r][c+1]=='E'){
next.a = l;
next.b = r;
next.d = c+1;
next.ans = now.ans+1;
q.push(next);
}
if(r>0&&(m[l][r-1][c]=='.'||m[l][r-1][c]=='E')){
next.a = l;
next.b = r-1;
next.d = c;
next.ans = now.ans+1;
q.push(next);
}
if(c>0&&(m[l][r][c-1]=='.'||m[l][r][c-1]=='E')){
next.a = l;
next.b = r;
next.d = c-1;
next.ans = now.ans+1;
q.push(next);
}
}
return -1;
}
void found()
{
for(int l=0;l<L;l++){
for(int r=0;r<R;r++){
for(int c=0;c<C;c++){
if(m[l][r][c]=='S'){
s.a=l;s.b=r;s.d=c;
return;
}
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&L,&R,&C)&&(L+R+C)){
memset(m,0,sizeof(m));
for(int l=0;l<L;l++){
for(int r=0;r<R;r++){
scanf("%s",m[l][r]);
}
getchar();
}
found();
int ans = bfs();
if(ans!=-1) printf("Escaped in %d minute(s).\n",ans);
else printf("Trapped!\n");
}
return 0;
}
问题就出在了我用结构体中的元素记录步数 导致重复计算 超内存了
如果改成用一个数组记录出发点到当前点的最短步数 即可避免之后的重复计算
AC代码如下
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 99999
using namespace std;
char m[35][35][35];
int dis[35][35][35];
int L,R,C;
struct coor
{
int a,b,d;
}s,e;
int mov[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int bfs()
{
memset(dis,0,sizeof(dis));
queue<coor>q;
q.push(s);
while(!q.empty()){
coor now = q.front();
int l = now.a;
int r = now.b;
int c = now.d;
q.pop();
coor n;
for(int i=0;i<6;i++){
n.a = l+mov[i][0];
n.b = r+mov[i][1];
n.d = c+mov[i][2];
if(n.a>=0&&n.a<L&&n.b>=0&&n.b<R&&n.d>=0&&n.d<C&&m[n.a][n.b][n.d]!='#'&&dis[n.a][n.b][n.d]==0){
dis[n.a][n.b][n.d] = dis[l][r][c]+1;
q.push(n);
if(m[n.a][n.b][n.d]=='E') return dis[n.a][n.b][n.d];
}
}
}
return -1;
}
void foundS()
{
for(int l=0;l<L;l++){
for(int r=0;r<R;r++){
for(int c=0;c<C;c++){
if(m[l][r][c]=='S'){
s.a=l;s.b=r;s.d=c;
return;
}
}
}
}
}
void foundE()
{
for(int l=0;l<L;l++){
for(int r=0;r<R;r++){
for(int c=0;c<C;c++){
if(m[l][r][c]=='E'){
e.a=l;e.b=r;e.d=c;
return;
}
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&L,&R,&C)&&(L+R+C)){
memset(m,0,sizeof(m));
for(int l=0;l<L;l++){
for(int r=0;r<R;r++){
scanf("%s",m[l][r]);
}
getchar();
}
foundS();
foundE();
int ans = bfs();
if(ans!=-1) printf("Escaped in %d minute(s).\n",ans);
else printf("Trapped!\n");
}
return 0;
}
还有一点 我一开始没意识到是有6种方向而不是5种 还有返回上一楼层这种操作