1. 程式人生 > >搜索模板(DFS/BFS)

搜索模板(DFS/BFS)

個數 while d+ nod div ++ int second code

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)