最短路径一定要用BFS,
DFS求最短路径不及BFS系列
阅读(13) | 评论(0) | 转发(0) |
<script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=3&lang=zh"></script> <script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/bshareC0.js"></script>
DFS求最短路径不及BFS系列
点击(此处)折叠或打开
- #include <iostream>
- #include <stdio.h>
- #include <cstring>
- #include <queue>
-
- using namespace std;
-
- #define MAX_V (40+1)
- struct point{
- int x;
- int y;
- int z;
- int l;
- };
-
- char T[MAX_V][MAX_V][MAX_V];
- char V[MAX_V][MAX_V][MAX_V];
-
- int l,r,c;
- int si,sj,sk;
-
- struct move{
- int x;
- int y;
- int z;
- }MOVE[]={ {-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };
-
- int ml = sizeof(MOVE) /sizeof(move);
-
- int bfs()
- {
-
- struct point Q[50000];
- Q[0].x=si;
- Q[0].y=sj;
- Q[0].z=sk;
- Q[0].l=1;
- int h=0,t=1;
-
- memset(V,0,sizeof(V));
- V[si][sj][sk]=1;
-
- while(h<t)
- {
- //point p=Q.front();
- //Q.pop();
- point p=Q[h];
- h++;
- //printf("(%d,%d,%d)=%d\n",p.x,p.y,p.z,p.l);
- //V[x][y][z]=1; //习惯性的再这里加访问标志
//如果不是求最小生成树等BFS变种,其实一个元素放到队列里,就是已经访问了。
- for(int m=0;m<ml;m++)
- {
- int x=MOVE[m].x + p.x;
- int y=MOVE[m].y + p.y;
- int z=MOVE[m].z + p.z;
-
- if( x < 1 || y < 1 || z < 1)
- continue;
-
- if(x > l || y > r || z > c)
- continue;
-
- if(V[x][y][z] != 0)
- continue;
-
- if(T[x][y][z] == 'E')
- return p.l;
-
- if(T[x][y][z] == '.')
- {
- Q[t].x=x;
- Q[t].y=y;
- Q[t].z=z;
- Q[t].l=p.l+1;
- t++;
- V[x][y][z]=1; //所以BFS的visit应该放在这里设标志。这样可以减少很多出队入队操作,也避免重复
- }
- }
-
- }
-
- return -1;
- }
- int main()
- {
- while(cin>>l>>r>>c)
- {
- if(l <= 0)
- return 0;
- for(int i=1;i<=l;i++)
- {
- for(int j=1;j<=r;j++)
- {
- for(int k=1;k<=c;k++)
- {
- char c;
- cin>>c;
- T[i][j][k]=c;
- //printf("read (%d,%d,%d)=%c\n",i,j,k,(char)T[i][j][k]);
- if( T[i][j][k] == 'S')
- {
- si=i;
- sj=j;
- sk=k;
- }
- }
- }
- }
-
- int ret = bfs();
- if(ret < 0)
- cout<<"Trapped!"<<endl;
- else
- cout<<"Escaped in "<<ret<<" minute(s)."<<endl;
- }
- }
相关热门文章
给主人留下些什么吧!~~
评论热议