首页 > 其他 > 详细

搜索模板(DFS/BFS)

时间:2017-08-22 14:16:56      阅读:238      评论:0      收藏:0      [点我收藏+]

DFS

int b[4][2] = {-1,0,0,1,1,0,0,-1};

int DFS( pair<int,int> x )
{
    int res=0;
    visited[x.first][x.second]=1;
    for( int i=0;i<4;i++ ){
        pair<int,int> tmp;
        tmp.first=x.first+b[i][0];
        tmp.second=x.second+b[i][1];
        if( check(tmp) )
        {
            visited[tmp.first][tmp.second]=1;
            res+=DFS(tmp);
        }
    }
    return res+1;//返回棋盘中所有能走的点的个数(红黑树)
}

BFS

struct Node
{
    int x,y,step;
}Node[maxn];
int dire[4][2]={-1,0,0,-1,1,0,0,1};

void BFS()
{
    queue<Node> que;
    Node p;
    p.x=st.x;
    p.y=st.y;
    p.step=0;
    que.push(p);
    visited[p.x][p.y]=1;
    while(!que.empty()){
        Node tmp=que.front();
        que.pop();
        if( tmp.x=ed.x && tmp.y=ed.y ){
            ans=tmp.step;
            break;
        }
        for( int i=0;i<4;i++ ){
            Node t;
            t.x=tmp.x+dire[i][0];
            t.y=tmp.y+dire[i][1];
            if( check(t) ){
                visited[t.x][t.y]=1;
                t.step=tmp.step+1;
                que.push(t);
            }
        }
    }
}

 

搜索模板(DFS/BFS)

原文:http://www.cnblogs.com/Dawn-SS/p/7411293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!