搜索模板

广搜模板

BFS在求解最短路径或者最短步数上有很多的应用。
用最多的是在走迷宫上。

int s[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
struct node
{
    int x,y;
    int step;
}cur;
void BFS()
{
    queue<node> Q;
    cur.x = sx;
    cur.y = sy;   //广搜开始位置sx,sy为全局变量
    cur.step = 0;
    Q.push(cur);
    while(!Q.empty())
    {
        node p = Q.front();
        Q.pop();
        if(满足条件)
        {
            .....
            return;
        }
        for(int i = 0; i < 4; i ++) //四个方向开始搜索
        {   node pre;
            pre =p;
            pre.x += s[i][0];
            pre.y += s[i][1];
            if(pre.x >= 0 && pre.x < n && pre.y >= 0 && pre.y < m &&!vis[pre.x][pre.y])  //判断广搜的边界和是否访问过
            {
                pre.step++;
                vis[pre.x][pre.y]=1;  //标记位
                Q.push(pre);
            }
        }
    }
}

深搜模板

void dfs(int x,int y)
{
    int i,j,xx,yy;
    num++;        //搜索的深度
    map[x][y]=1;  //标记位
    if(满足条件)
    {
        .....
        return;
    }
    else for(i=0; i<4; i++)//四个方向优先深度搜索
        {
            xx=x+f[i][0];
            yy=y+f[i][1];
            if(xx>=0&&yy>=0&&xx<5&&yy<5&&map[xx][yy]!=1)//搜索范围及是否搜过
                dfs(xx,yy);
        }
}

深搜+回溯

void dfs(int dep,int x,int y)  
{  
    int tx,ty;  
    if(满足条件)  
    {  
        。。。。
        return;  
    }  
    else  
    {  
        for(int i=1;i<=4;i++)  
        {  
            tx=dx[i]+x;  
            ty=dy[i]+y;  
            if( 边界限制 && !set[tx][ty] )   
            {  
                set[tx][ty]=true;  
                dfs(dep+1,tx,ty);  
                set[tx][ty]=false;  
            }  
        }  
    }  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值