BFS——广度优先搜索

BFS的模板

请添加图片描述

什么是bfs:

广度优先搜索,在搜索过程中由近及远,层层搜索。

从一个简单问题开始:

首先,看一个最简单的01迷宫:

1 1 1 0 0
1 0 1 1 0
1 0 1 1 0
1 1 0 1 0

起 点 : ( 1 , 1 ) {\color{red}起点:(1,1)} (1,1)
终 点 : ( 5 , 5 ) {\color{red}终点:(5,5)} (5,5)

要求我们输出从起点走到终点的最小步数。
不妨先给出代码,然后层层分析。

模板代码:

#include<iostream>
using namespace std;
const int MAXN = 200;
struct node{
    int x;
    int y;
    int step;
}que[MAXN*MAXN];
int g[MAXN][MAXN];
int n,m,head,tail;
bool book[MAXN][MAXN];
int ne[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};
void bfs()
{
    head = 0,tail = -1;
    que[++tail].x = 1;
    que[tail].y = 1;
    que[tail].step = 0;
    book[1][1] = true;
    while(tail>=head)
    {
        auto temp = que[head++];
        if(temp.x==n&&temp.y==m)
        {
            cout<<temp.step;
            return ;
        }
        for(int i = 0; i < 4 ; i++)
        {
            int tx = temp.x+ne[i][0];
            int ty = temp.y+ne[i][1];
            if(tx<1||ty<1||tx>n||ty>m||g[tx][ty]==1||book[tx][ty])
                continue;
            else
            {
                que[++tail].x = tx;
                que[tail].y = ty;
                que[tail].step = temp.step+1;
                book[tx][ty] = true;
//                cout<<que[tail].x<<" " <<que[tail].y<<" "<<que[tail].step<<endl;
            }
        }
    }
}
int main()
{
    cin>>n>>m;
    for(int i = 1 ; i <= n ; i++)
    {
        for(int j = 1; j <= m ; j++)
        {
            cin>>g[i][j];
        }
    }
    bfs();
    return 0;
}

代码的分析:
1.手写队列的使用:

//伪代码
tail >= head//队列判空

tail++
que[tail] = (x,y);//入队

node = que[head]//出队
head++  

2.从起点向四周拓展的方式:

int ne[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};
for(int i = 0 ; i < 4 ; i++)
{
	int tx = temp.x+ne[i][0];
	int ty = temp.y+ne[i][1];
}

3.判断拓展出的点是否合法:

if(tx<1||ty<1||tx>n||ty>m||g[tx][ty]==1||book[tx][ty])continue;
//不合法就不进行拓展

4.避免重复地拓展相同的点:

book[tx][ty] = true;

5.判断是否走至终点并输出最小步数:

if(temp.x==n&&temp.y==m)
{
    cout<<temp.step;
	return;
}       
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值