bfs算法模版

bfs算法模版

写过很多bfs题,每次写bfs代码习惯都略有不同,有些糟糕的代码习惯影响了解题速度

下面这份简单的三维bfs可以算是写得比较不错的一份了,以后按这种习惯写,虽然没有写回溯路径,但回溯路径很简单,只要加个fa数组就行了,所以就不加在模版上了

//bfs模版
int X,Y,Z;
char ch[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int sx,sy,sz;
int ans;
int dx[]={-1,1,0,0,0,0};
int dy[]={0,0,-1,1,0,0};
int dz[]={0,0,0,0,-1,1};

struct node
{
    int x,y,z;
    int dist;
};

bool bfs()
{
    queue<node> q;
    q.push({sx,sy,sz,0});
    vis[sx][sy][sz]=1;
    while(!q.empty()){
        node now=q.front();
        q.pop();
        for(int i=0;i<6;i++){
            int nx=now.x+dx[i];
            int ny=now.y+dy[i];
            int nz=now.z+dz[i];
            int nd=now.dist+1;
            if(ch[nx][ny][nz]=='E'){
                ans=nd;
                return true;
            }
            if(ch[nx][ny][nz]=='#') continue;
            if(vis[nx][ny][nz]) continue;
            vis[nx][ny][nz]=1;
            q.push({nx,ny,nz,nd});
        }
    }
    return false;
}
bfs模版

 

posted @ 2015-03-13 14:43  __560  阅读(408)  评论(0编辑  收藏  举报