DFS/BFS视频讲解

视频链接:https://www.bilibili.com/video/av12019553?share_medium=android&share_source=qq&bbid=XZ70A217A7087163A06D3DB55EDA08CB8565B&ts=1550904940091

 

 

DFS和BFS其实都是一棵搜索树,大多数题目不会直接给你一棵树,需要你自己转化

 

DFS

 

BFS

模板:

void bfs(int x,int y)
{
    node temp;
    temp.x=x;
    temp.y=y;
    temp.step=0;
    queue<node>p;
    p.push(temp);
    vis[x][y]=1;
    while(!p.empty())
    {
        node now=p.front();
        p.pop();
        for(int i=0;i<4;i++)
        {
            int tx=now.x+dir[i][0];
            int ty=now.y+dir[i][1];
            if(合法条件)
            {
                if(目标状态)
                {
                    cout<<结果<<endl;
                    return ;
                }
                //更新状态
                /*vis[tx][ty]=1;
                node temp;------------注意不能直接用now更新,这里要新建一个结构体去更新,否则会错
                temp.x=tx;
                temp.y=ty;
                temp.step=now.step+1;*/
                p.push(temp);
            }
        }
    }
}

 

 

 

 

 

posted @ 2019-02-23 16:09  知道了呀~  阅读(390)  评论(0编辑  收藏  举报