标签:bfs
题意:这题从二维空间扩展到三维空间了,可以上下左右前后移动,每次都只能移到相邻的空位,
每次需要花费一分钟,求从起点到终点最少要多久
#表示岩石,.表示空位,S是起点,E是终点
这题只需要从6个方向bfs是行了,开始一直超时,改成dfs就wa,
之后发现每次访问后应立即标记为已访问、、、我是通过将访问的点变成#即岩石,来标记已访问的
#include<cstdio> #include<cstring> #include<queue> using namespace std; struct stu { int i,j,k; }; char s[35][35][35]; int m,n,p; int bfs(struct stu a,struct stu b) { int i,j,k,t[35][35][35]={0}; queue<struct stu> q; q.push(a); s[a.i][a.j][a.k]='#'; while(!q.empty()){ a=q.front(); q.pop(); i=a.i; j=a.j; k=a.k; if(i==b.i&&j==b.j&&k==b.k) //到达终点结束 return t[i][j][k]; if(i>0&&s[i-1][j][k]!='#'){ a.i=i-1; a.j=j; a.k=k; q.push(a); t[i-1][j][k]=t[i][j][k]+1; //计算时间 s[i-1][j][k]='#'; //记得访问后要立即标记 } if(i<m-1&&s[i+1][j][k]!='#'){ a.i=i+1; a.j=j; a.k=k; q.push(a); t[i+1][j][k]=t[i][j][k]+1; s[i+1][j][k]='#'; } if(j>0&&s[i][j-1][k]!='#'){ a.i=i; a.j=j-1; a.k=k; q.push(a); t[i][j-1][k]=t[i][j][k]+1; s[i][j-1][k]='#'; } if(j<n-1&&s[i][j+1][k]!='#'){ a.i=i; a.j=j+1; a.k=k; q.push(a); t[i][j+1][k]=t[i][j][k]+1; s[i][j+1][k]='#'; } if(k>0&&s[i][j][k-1]!='#'){ a.i=i; a.j=j; a.k=k-1; q.push(a); t[i][j][k-1]=t[i][j][k]+1; s[i][j][k-1]='#'; } if(k<p-1&&s[i][j][k+1]!='#'){ a.i=i; a.j=j; a.k=k+1; q.push(a); t[i][j][k+1]=t[i][j][k]+1; s[i][j][k+1]='#'; } } return -1; //若不可能到达终点,则返回-1 } int main() { int i,j,k,sum; struct stu x,y; while(scanf("%d%d%d",&m,&n,&p)!=EOF){ getchar(); if(m==0&&n==0&&p==0) break; for(i=0;i<m;i++){ for(j=0;j<n;j++){ for(k=0;k<p;k++){ scanf("%c",&s[i][j][k]); if(s[i][j][k]=='S'){ x.i=i; x.j=j; x.k=k; } else if(s[i][j][k]=='E'){ y.i=i; y.j=j; y.k=k; } } getchar(); } getchar(); } sum=bfs(x,y); if(sum!=-1) printf("Escaped in %d minute(s).\n",sum); else printf("Trapped!\n"); } return 0; }
poj 2251 Dungeon Master(bfs),布布扣,bubuko.com
标签:bfs
原文地址:http://blog.csdn.net/acm_code/article/details/37909069