BFS题目学习总结

来源:互联网 发布:澳大利亚怎么淘宝 编辑:程序博客网 时间:2024/05/18 01:03

博文持续更新中,记录BFS类题目的总结,不断学习,不断记录。

(1)hdu1253胜利大逃亡 http://acm.hdu.edu.cn/showproblem.php?pid=1253

思路:简单的bfs,但是我写这个题卡了一下午,简直要崩溃了,要总结下,不要乱用memset去填充,wtf程序老师莫名的崩掉;要熟练运用continue;要分清if  if else if;最重要的就是能用scanf尽量用scanf,一开始用cin各种TLE,真的要疯了。

代码:

#include <iostream>#include <queue>#include <cstdio>using namespace std;int a,b,c,t;int Map[51][51][51];int dir[6][3]= {{1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};struct point{    int x,y,z;    int time;};int dfs(){    if(a==1&&b==1&&c==1)        return 0;    queue<point>Q;    point start;//定义起始点    start.x=start.y=start.z=start.time=0;    Q.push(start);Map[0][0][0]=1;    point now,next;//dingyi    while(!Q.empty()){        now=Q.front();Q.pop();        for(int i=0;i<6;i++){            next.x=now.x+dir[i][0];            next.y=now.y+dir[i][1];            next.z=now.z+dir[i][2];            next.time=now.time+1;            if(next.x<0||next.x>=a||next.y<0||next.y>=b||next.z<0||next.z>=c)                continue;            if(Map[next.x][next.y][next.z]==0){                if(next.x==a-1&&next.y==b-1&&next.z==c-1)                    return next.time;                Q.push(next);                Map[next.x][next.y][next.z]=1;            }        }    }    return -1;}int main(){    int N;scanf("%d",&N);    while(N--){        scanf("%d%d%d%d",&a,&b,&c,&t);        for(int i=0;i<a;i++)            for(int j=0;j<b;j++)                for(int k=0;k<c;k++)                scanf("%d",&Map[i][j][k]);        if(a+b+c-3>t){            printf("-1\n");            continue;        }        if(Map[a-1][b-1][c-1]==1){            printf("-1\n");            continue;        }        int ans=dfs();        if(ans<=t)            printf("%d\n",ans);        else            printf("-1\n");    }}

1 0
原创粉丝点击