BFS总结

BFS:找到的路径长度一定是起点到终点的最短路径

构思BFS的步骤:

1、确定队列结构体要记录什么东西,一般为x,y坐标,累加的路径长度r

2、确定入队条件

3、确定终结条件

 

模板:

int map[M][M],wan[M][M]; //map是图;wan是弯的数量,主要用来剪枝
int go[4][2]= {{-1,0},{1,0},{0,-1},{0,1}}; //go表示走上、下、左、右方向

struct node
{
    int x,y,turn,road;
    node() {}
    node(int a,int b,int c,int d) //构造函数
    {
        x=a;
        y=b;
        turn=c;
        road=d;
    }
};
bool bfs()
{
    for(int i=1; i<=R; ++i)  //初始化wan
        for(int j=1; j<=C; ++j)
            wan[i][j]=inf;
    queue<node> Q;
    node f(s_x,s_y,-1,6); //入队的首元素
    Q.push(f);
    while(!Q.empty()&&!F)
    {
        node s=Q.front();
        Q.pop();
        for(int i=0; i<4; ++i)
        {
            int nx=s.x+go[i][0];
            int ny=s.y+go[i][1];
            if(nx<1||nx>R||ny<1||ny>C||map[nx][ny]!=0||t>2||t>wan[nx][ny]) //入队条件
                continue;
            wan[nx][ny]=t;
            node p(nx,ny,t,i);
            Q.push(p); //满足以上苛刻条件的点入队
        }
    }
}

附加优先队列:
struct node
{
    friend bool operator< (node n1, node n2) //按照priority从大到小排列
    {
        return n1.priority < n2.priority; //important
    }
    int priority;
    int value;
};
priority_queue<node> Q;

 

A*

struct point
{
    int x,y;
    int sum,yu;
    friend bool operator<(point a,point b)
    {
        return a.sum+a.yu>b.sum+b.yu;
    }
    point(int a,int b,int c)
    {
        x=a;y=b;sum=c;
        yu=abs(ei-a)+abs(ej-b);
    }
};

int afs(int x,int y)
{
    priority_queue<point> Q;
    point f(x,y,0);
    Q.push(f);
    while(!Q.empty())
    {
        point t=Q.top();
        Q.pop();
        for(int i=0;i<4;i++)
        {
            int nx=t.x+go[i][0];
            int ny=t.y+go[i][1];
            if(nx<0||nx>=h||ny<0||ny>=w) continue;
            if(ma[nx][ny]=='#') continue;
            int temp=re[t.x][t.y]+1;
            if(ma[nx][ny]=='@') temp+=d;
            if(temp>=re[nx][ny]&&re[nx][ny]>=0) continue;
            point next(nx,ny,temp);
            re[nx][ny]=temp;
            Q.push(next);
            if(nx==ei&&ny==ej) return re[ei][ej]+1;
        }
    }
    return re[ei][ej]+1;
}

 

转载于:https://www.cnblogs.com/A-way/archive/2013/04/13/3019143.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值