BFS 广度优先搜索

BFS 广度优先搜索

广度优先搜索我还是看的“一只会code的小金鱼”这个b站up主学的。本人看了他入门课的第一题之后开始写的题,后面的没看,所以可能和他写的不一样,请见谅。在这里先给想要看视频学习的小伙伴们打个预防针,就是视频的时长一般都很长,而且由于是直播录播,可能有些时间浪费在理解up主错误的代码上。(当然我也不能保证我没有错误,但是可能会比他的错误少一些,也欢迎各位佬来帮我指正、完善) 还有一点学习建议就是,先学一下stl中queue的使用,这样也方便看懂代码。还有,标题处都有题目链接,点击就可跳转。 最后着重强调,代码一定要自己敲一遍,不是边看边敲,是看懂了之后,过一段时间自己再敲,东西才是自己的。

走迷宫

题目

给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。

最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。

数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。

输入格式

第一行包含两个整数 n 和 m。

接下来 n 行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。

输出格式

输出一个整数,表示从左上角移动至右下角的最少移动次数。

数据范围

1≤n,m≤100

输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:
8

题解

相关步骤的一些注释,我都在代码中写出来了。

//头文件不一定全都要,只是我个人的习惯,当然你也可以用万能头
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <cstring>
#define int long long

using namespace std;

int n, m;
const int N = 101;

//为了存储点的坐标
typedef pair<int, int> PII;
queue<PII> q;

int arr[N][N] = { 0 };	//记录迷宫
int dis[N][N];		//记录迷宫每个点到原点的距离

//这是用来确定移动方向的
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };

int bfs(int x, int y) {
    memset(dis, -1, sizeof(dis));	//这是给数组初始化为-1,用来记录距离的同时确定该位置有没有到达过
    q.push({ x, y });	//把坐标填入队列
    dis[x][y] = 0;

    while (!q.empty()) {
        auto t = q.front();		//取队首元素
        q.pop();	//弹出队首元素

        for (int i = 0; i < 4; i++) {
            //按照规则走
            int a = t.first + dx[i], b = t.second + dy[i];
            //判断能不能走
            if (a <= 0 || a > n || b <= 0 || b > m) continue;
            if (arr[a][b] != 0) continue;
            if (dis[a][b] >= 0) continue;
		   //如果能走,放进队列,更新距离
            q.push({ a, b });
            dis[a][b] = dis[t.first][t.second] + 1;
        }
    }
    return dis[n][m];
}

signed main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> arr[i][j];
        }
    }
    int ans = bfs(1,1);
    cout << ans << endl;

    return 0;
}

P1746 离开中山路

题目

题目背景

《爱与愁的故事第三弹·shopping》最终章。

题目描述

爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 x 1 , y 1 x_1,y_1 x1,y1 处,车站在 x 2 , y 2 x_2,y_2 x2,y2 处。现在给出一个 n × n ( n ≤ 1000 ) n \times n(n \le 1000) n×n(n1000) 的地图, 0 0 0 表示马路, 1 1 1 表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(每两个相邻坐标间距离为 1 1 1)。你能帮他解决吗?

输入格式

1 1 1 行包含一个数 n n n

2 2 2 行到第 n + 1 n+1 n+1 行:整个地图描述( 0 0 0 表示马路, 1 1 1 表示店铺,注意两个数之间没有空格)。

n + 2 n+2 n+2 行:四个数 x 1 , y 1 , x 2 , y 2 x_1,y_1,x_2,y_2 x1,y1,x2,y2

输出格式

只有 1 1 1 行,即最短到达目的地距离。

输入输出样例 #1
输入 #1
3
001
101
100
1 1 3 3
输出 #1
4
说明/提示

对于 20 % 20\% 20% 数据,满足 1 ≤ n ≤ 100 1\leq n \le 100 1n100

对于 100 % 100\% 100% 数据,满足 1 ≤ n ≤ 1000 1\leq n \le 1000 1n1000

题解

这里有几点注意,y1不能作为变量名,起码我用vs2022和洛谷都报错了。并且,注意题目输入的是字符串,我在这调了很久。然后,这段代码我没写注释,试试看能不能看懂,这和第一题差不多。(才不是懒得写注释)

#include <iostream>
#include <cstring>
#include <queue>
#define int long long

using namespace std;

typedef pair<int, int> PII;
queue<PII> q;

int n;
int x, x2, y, y2;
int x_0[] = { 0, 1, 0, -1 };
int y_0[] = { 1, 0, -1, 0 };
int arr[1001][1001] = { 0 };
int dis[1001][1001] = { 0 };

int bfs() {
    memset(dis, -1, sizeof(dis));
    q.push({ x, y });
    dis[x][y] = 0;

    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 4; i++) {
            int a = t.first + x_0[i];
            int b = t.second + y_0[i];
            if (a <= 0 || a > n || b <= 0 || b > n) continue;
            else if (arr[a][b] == 1) continue;
            else if (dis[a][b] != -1) continue;

            q.push({ a, b });
            dis[a][b] = dis[t.first][t.second] + 1;
        }
    }
    return dis[x2][y2];
}

signed main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n;
    for (int i = 1; i <= n; i++) {
        string s;
        cin >> s;
        for (int j = 1; j <= n; j++) {
            arr[i][j] = s[j - 1] - '0';
        }
    }
    cin >> x >> y >> x2 >> y2;

    int ans = bfs();
    cout << ans << endl;

    return 0;
}

P1443 马的遍历

题目

题目描述

有一个 n × m n \times m n×m 的棋盘,在某个点 ( x , y ) (x, y) (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。

输入格式

输入只有一行四个整数,分别为 n , m , x , y n, m, x, y n,m,x,y

输出格式

一个 n × m n \times m n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 − 1 -1 1)。

输入输出样例 #1
输入 #1
3 3 1 1
输出 #1
0    3    2    
3    -1   1    
2    1    4
说明/提示
数据规模与约定

对于全部的测试点,保证 1 ≤ x ≤ n ≤ 400 1 \leq x \leq n \leq 400 1xn400 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1ym400

题解

说实话,这道题出的有点恶心,先把题目的坑说清楚了,免的各位花费不必要的精力。首先,这个马是象棋中的走日字格的马。其次,输出其实限制场宽,大小是五,而且最好不要用cpp的方法,因为还要左对齐。(作者不会)

#include <bits/stdc++.h>
#define int long long

using namespace std;

typedef pair<int,int> PII;
queue<PII> q;

int n, m, x, y;
int arr[401][401] = {0};
int dis[401][401];
int dx[] = {2, 1, -2, 1, 2, -2, -1, -1};
int dy[] = {1, -2, 1, 2, -1, -1, 2, -2};

void bfs() {
    memset(dis, -1, sizeof(dis));
    q.push({x, y});
    dis[x][y] = 0;

    while(!q.empty()) {
        auto t = q.front();
        q.pop();

        for(int i = 0; i < 8; i++) {
            int a = t.first + dx[i];
            int b = t.second + dy[i];

            if(a <= 0 || a > n || b <= 0 || b > m) continue;
            else if(dis[a][b] != -1) continue;

            q.push({a, b});
            dis[a][b] = dis[t.first][t.second] + 1; 
        }
    }
}


signed main(void)
{
    scanf("%lld %lld %lld %lld", &n, &m, &x, &y);
    bfs();
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= m; j++) {
            printf("%-5lld", dis[i][j]);
        }
        printf("\n");
    }

    return 0;
}

P1747 好奇怪的游戏

题目

题目背景

《爱与愁的故事第三弹·shopping》娱乐章。调调口味来道水题。

题目描述

爱与愁大神坐在公交车上无聊,于是玩起了手机。一款奇怪的游戏进入了爱与愁大神的眼帘:***(游戏名被打上了马赛克)。这个游戏类似象棋,但是只有黑白马各一匹,在点 x 1 , y 1 x_1,y_1 x1,y1 x 2 , y 2 x_2,y_2 x2,y2 上。它们得从点 x 1 , y 1 x_1,y_1 x1,y1 x 2 , y 2 x_2,y_2 x2,y2 走到 ( 1 , 1 ) (1,1) (1,1)。这个游戏与普通象棋不同的地方是:马可以走“日”,也可以像象走“田”。现在爱与愁大神想知道两匹马到 ( 1 , 1 ) (1,1) (1,1) 的最少步数,你能帮他解决这个问题么?

注意不能走到 x x x y y y 坐标 ≤ 0 \le 0 0 的位置。

输入格式

第一行两个整数 x 1 , y 1 x_1,y_1 x1,y1

第二行两个整数 x 2 , y 2 x_2,y_2 x2,y2

输出格式

第一行一个整数,表示黑马到 ( 1 , 1 ) (1,1) (1,1) 的步数。

第二行一个整数,表示白马到 ( 1 , 1 ) (1,1) (1,1) 的步数。

输入输出样例 #1
输入 #1
12 16
18 10
输出 #1
8 
9
说明/提示
数据范围及约定

对于 100 % 100\% 100% 数据, 1 ≤ x 1 , y 1 , x 2 , y 2 ≤ 20 1\le x_1,y_1,x_2,y_2 \le 20 1x1,y1,x2,y220

题解

做过前面几道题再做这道,应该是比较简单的,就不过多赘述了。

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

typedef pair<int, int> PII;
queue<PII> q;

int dis[21][21];
int x_1, y_1, x_2, y_2;
int dx[] = { 2, 1, -2, 1, 2, -2, -1, -1, 2, -2, -2, 2 };
int dy[] = { 1, -2, 1, 2, -1, -1, 2, -2, 2, -2, 2, -2 };


int bfs(int x, int y) {
    memset(dis, -1, sizeof dis);
    dis[x][y] = 0;
    q.push({ x, y });
    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 12; i++) {
            int a = t.first + dx[i];
            int b = t.second + dy[i];
            if (a >= 1 && a <= 20 && b >= 1 && b <= 20 && dis[a][b] == -1) {
                dis[a][b] = dis[t.first][t.second] + 1;
                q.push({ a, b });
            }
        }
    }
    return dis[1][1];
}

int main() {
    cin >> x_1 >> y_1;
    cin >> x_2 >> y_2;

    int ansh = bfs(x_1, y_1);
    int ansb = bfs(x_2, y_2);

    cout << ansh << endl << ansb << endl;
    return 0;
}

P1332 血色先锋队

题目

题目背景

巫妖王的天灾军团终于卷土重来,血色十字军组织了一支先锋军前往诺森德大陆对抗天灾军团,以及一切沾有亡灵气息的生物。孤立于联盟和部落的血色先锋军很快就遭到了天灾军团的重重包围,现在他们将主力只好聚集了起来,以抵抗天灾军团的围剿。可怕的是,他们之中有人感染上了亡灵瘟疫,如果不设法阻止瘟疫的扩散,很快就会遭到灭顶之灾。大领主阿比迪斯已经开始调查瘟疫的源头。原来是血色先锋军的内部出现了叛徒,这个叛徒已经投靠了天灾军团,想要将整个血色先锋军全部转化为天灾军团!无需惊讶,你就是那个叛徒。在你的行踪败露之前,要尽快完成巫妖王交给你的任务。

题目描述

军团是一个 n n n m m m 列的矩阵,每个单元是一个血色先锋军的成员。感染瘟疫的人,每过一个小时,就会向四周扩散瘟疫,直到所有人全部感染上瘟疫。你已经掌握了感染源的位置,任务是算出血色先锋军的领主们感染瘟疫的时间,并且将它报告给巫妖王,以便对血色先锋军进行一轮有针对性的围剿。

输入格式

1 1 1 行:四个整数 n n n m m m a a a b b b,表示军团矩阵有 n n n m m m 列。有 a a a 个感染源, b b b 为血色敢死队中领主的数量。

接下来 a a a 行:每行有两个整数 x x x y y y,表示感染源在第 x x x 行第 y y y 列。

接下来 b b b 行:每行有两个整数 x x x y y y,表示领主的位置在第 x x x 行第 y y y 列。

输出格式

1 1 1 b b b 行:每行一个整数,表示这个领主感染瘟疫的时间,输出顺序与输入顺序一致。如果某个人的位置在感染源,那么他感染瘟疫的时间为 0 0 0

输入输出样例 #1
输入 #1
5 4 2 3
1 1
5 4
3 3
5 3
2 4
输出 #1
3
1
3
说明/提示
输入输出样例 1 解释

如下图,标记出了所有人感染瘟疫的时间以及感染源和领主的位置。

数据规模与约定

对于 100 % 100\% 100% 的数据,保证 1 ≤ n , m ≤ 500 1\le n,m\le500 1n,m500 1 ≤ a , b ≤ 1 0 5 1\le a,b\le10^5 1a,b105

题解

这是一道多元的bfs,但其实没有什么变化,就是换成用数组存储了。下面直接上代码。

#include <bits/stdc++.h>
#define int long long

using namespace std;
typedef pair<int,int> PII;
queue<PII> q;

int n, m, a, b;
PII pan[100001];
PII ling[100001];
int dis [501][501];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

void bfs() {
    memset(dis, -1, sizeof dis);
    for(int i = 0; i < a; i++) {
        dis[pan[i].first][pan[i].second] = 0;
    }
    for(int i = 0; i < a; i++) {
        q.push({pan[i].first,pan[i].second});
    }
    while(!q.empty()) {
        auto t = q.front();
        q.pop();
        for(int i = 0; i < 4; i++) {
            int c = t.first + dx[i];
            int d = t.second + dy[i];

            if(c <= 0 || c > n || d <= 0 || d > m) continue;
            if(dis[c][d] != -1) continue;
            q.push({c, d});
            dis[c][d] = dis[t.first][t.second] + 1;
        }
    }
}

signed main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m >> a >> b;
    for(int i = 0; i < a; i++) {
        int c, d;
        cin >> c >> d;
        pan[i] = {c, d};
    }
    for(int i = 0; i < b; i++) {
        int c, d;
        cin >> c >> d;
        ling[i] = {c, d};
    }
    bfs();
    for(int i = 0; i < b; i++) {
        cout << dis[ling[i].first][ling[i].second] << endl;
    }
    
    return 0;
}

好了,现在来总结一下吧。个人觉得bfs入门比dfs入门简单,接下来就是两者的进阶了,希望和读者一起进步,加油。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

whimc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值