bfs模板

bfs模板:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
#define N 1000+5
char map[N][N];
bool visit[N][N];    //标记访问
int n, m;
int dx[4]={1, 0, -1, 0};
int dy[4]={0, 1, 0, -1};
struct point       //定义结构体
{
    int x, y;
    int ncount;     //记录步数
};
bool check(point a){      //检查是否符合要求
    if(a.x>=0&&a.x<n&&a.y>=0&&a.y<m&&!visit[a.x][a.y])   //视具体情况而定
        return true;
    else 
        return false;
}
void bfs(point a){
     queue<point>q;      //定义队列
     a.ncount=0;      //步数清零
     point now, next;      //定义两个状态
     q.push(a);               //将a压入队列
     visit[a.x][a.y]=1;     //标记已访问
     while(!q.empty()){      //判断是否为空队列
        now=q.front();              //取出队首元素
        if(now==G){        //出现目标状态,此时ncount最小
            .......//做出相关处理
            return ;
        }
        for(int i=0; i<4; i++){
            next.x=now.x+dx[i];
            next.y=now.y+dy[i];     //计算下一个状态
            next.ncount=now.ncount+1;
            if(check(next)){
                q.push(next);       //将next压入队列
                visit[next.x][next.y]=1;
            }
        }
        q.pop();     //移除队首元素
     }
     return ;
}
int main(){
    ......       //相关操作
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值