BFS入门刷题

news2025/6/4 0:17:15

目录

P1746 离开中山路

P1443 马的遍历

P1747 好奇怪的游戏

P2385 [USACO07FEB] Bronze Lilypad Pond B


P1746 离开中山路

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int n;
int startx, starty;
int endx, endy;
char a[1010][1010];
int dis[1010][1010];
queue<pair<int, int>> q;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};
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 < 4; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= n && ny <= n && a[nx][ny] != '1' && dis[nx][ny] <= 0)
            {
                q.push({nx, ny});
                dis[nx][ny] = dis[t.first][t.second] + 1;
            }
        }
    }
    return dis[endx][endy];
}
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cin >> a[i][j];
        }
    }
    cin >> startx >> starty >> endx >> endy;
    cout << bfs(startx, starty);
    return 0;
}

P1443 马的遍历

2个样例TLE:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};
int dis[410][410];
int n, m;
queue<pair<int, int>> q;
int startx, starty;
int bfs(int x, int y)
{
    if (x == startx && y == starty)
    {
        return 0;
    }
    memset(dis, -1, sizeof dis);
    q.push({startx, starty});
    dis[startx][starty] = 0;
    while (!q.empty())
    {
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= n && ny <= m && dis[nx][ny] <= 0)
            {
                q.push({nx, ny});
                dis[nx][ny] = dis[t.first][t.second] + 1;
            }
        }
    }
    return dis[x][y];
}
int main()
{
    cin >> n >> m >> startx >> starty;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cout << bfs(i, j) << " ";
        }
        cout << endl;
    }
    return 0;
}

作者一开始想的是每个点都要计数,所以每个点都要搜一次,然后返回一个值

其实只要搜一次

用void类型,不用返回,从开始搜到结尾,然后每个点都会一层一层地搜到,最后dis数组里存的就是每个点的计数

优化:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};
int dis[410][410];
int n, m;
queue<pair<int, int>> q;
int startx, starty;
void bfs(int x, int y)
{
    memset(dis, -1, sizeof dis);
    q.push({startx, starty});
    dis[startx][starty] = 0;
    while (!q.empty())
    {
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= n && ny <= m && dis[nx][ny] <= 0)
            {
                q.push({nx, ny});
                dis[nx][ny] = dis[t.first][t.second] + 1;
            }
        }
    }
}
int main()
{
    cin >> n >> m >> startx >> starty;
    bfs(startx, starty);
    dis[startx][starty] = 0;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cout << dis[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

调用STL中的queue调用坐标需要花费比较长的时间,我们可以用数组来模拟queue节省时间

再优化:

#include <iostream>
#include <cstring>
using namespace std;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};
int dis[410][410];
int n, m;
pair<int, int> q[410 * 410];
int startx, starty;
void bfs(int x, int y)
{
    memset(dis, -1, sizeof dis);
    int head = 0;
    int tail = 0;
    q[0] = {x, y};
    dis[x][y] = 0;
    while (head <= tail)
    {
        auto t = q[head++];
        for (int i = 0; i < 8; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= n && ny <= m && dis[nx][ny] <= 0)
            {
                q[++tail] = {nx, ny};
                dis[nx][ny] = dis[t.first][t.second] + 1;
            }
        }
    }
}
int main()
{
    cin >> n >> m >> startx >> starty;
    bfs(startx, starty);
    dis[startx][starty] = 0;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cout << dis[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

好像看不出什么区别

P1747 好奇怪的游戏

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int x1, y1;
int x2, y2;
int dis[30][30];
queue<pair<int, int>> q;
int dx[] = {1, 2, 2, 1, -1, -2, -2, -1, 2, 2, -2, -2};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2, 2, -2, -2, 2};
int bfs(int x, int y)
{
    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 < 12; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= 20 && ny <= 20 && dis[nx][ny] <= 0)
            {
                q.push({nx, ny});
                dis[nx][ny] = dis[t.first][t.second] + 1;
            }
        }
    }
    return dis[1][1];
}
int main()
{
    cin >> x1 >> y1 >> x2 >> y2;
    cout << bfs(x1, y1) << endl;
    cout << bfs(x2, y2) << endl;
    return 0;
}

P2385 [USACO07FEB] Bronze Lilypad Pond B

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
queue<pair<int, int>> q;
int m, n;
int m1, n1;
int a[35][35];
int dis[35][35];
int startx, starty, endx, endy;
int bfs(int x, int y)
{
    memset(dis, -1, sizeof dis);
    q.push({x, y});
    dis[x][y] = 0;
    while (!q.empty())
    {
        auto t = q.front();
        q.pop();
        int dx[] = {m1, m1, -m1, -m1, n1, n1, -n1, -n1};
        int dy[] = {n1, -n1, n1, -n1, m1, -m1, m1, -m1};
        for (int i = 0; i < 8; i++)
        {
            int nx = t.first + dx[i];
            int ny = t.second + dy[i];
            if (nx >= 1 && ny >= 1 && nx <= m && ny <= n && a[nx][ny] != 0 && a[nx][ny] != 2 && dis[nx][ny] == -1)
            {
                dis[nx][ny] = dis[t.first][t.second] + 1;
                q.push({nx, ny});
            }
        }
    }
    return dis[endx][endy];
}
int main()
{
    cin >> m >> n >> m1 >> n1;
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cin >> a[i][j];
            if (a[i][j] == 3)
            {
                startx = i;
                starty = j;
            }
            if (a[i][j] == 4)
            {
                endx = i;
                endy = j;
            }
        }
    }
    cout << bfs(startx, starty);
    return 0;
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2395588.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

UE5 编辑器工具蓝图

文章目录 简述使用方法样例自动生成Actor&#xff0c;并根据模型的包围盒设置Actor的大小批量修改场景中Actor的属性&#xff0c;设置Actor的名字&#xff0c;设置Actor到指定的文件夹 简述 使用编辑器工具好处是可以在非运行时可以对资源或场景做一些操作&#xff0c;例如自动…

数据仓库分层 4 层模型是什么?

企业每天都在产生和收集海量数据。然而&#xff0c;面对这些数据&#xff0c;许多企业却陷入了困境&#xff1a;如何高效管理、处理和分析这些数据&#xff1f;如何从数据中提取有价值的信息来支持业务决策&#xff1f;这些问题困扰着众多数据分析师和 IT 管理者。 在众多架构…

基于亚博K210开发板——物体分类测试

开发板 亚博K210开发板 实验目的 本次测试主要学习 K210 如何物体分类&#xff0c;然后通过 LCD 显示屏实时显示当前物体的分类名称。本节采用百度出的 PaddlePaddle 平台开发。 实验元件 OV2640 摄像头/OV9655 摄像头/GC2145 摄像头、LCD 显示屏 硬件连接 K210 开发板…

什么是缺页中断(缺页中断详解)

文章目录 【操作系统】什么是缺页中断&#xff08;缺页中断详解&#xff09;一、缺页中断的本质与背景1. **虚拟内存与分页机制**2. **缺页中断的定义** 二、缺页中断的触发场景1. **首次访问新分配的虚拟页**2. **内存置换导致的页缺失**3. **访问权限冲突**4. **页表项无效**…

【echarts】仪表盘

<div style"width:50%;height:33%"><Yibiaopan echart_id"ybpChart2" :series_data"gaugeData2" title"火电" unit"MWh" :colorList"[#DFA58F,#F89061,#FF8E59]" /></div> 链接&#xff1a;ht…

java27

1.IO流 FileOutPutStream字节输出流基本用法&#xff1a; 一次性写入一个字符串的内容&#xff1a; 注意&#xff1a;\r或者\n表示把普通的r或者n的字符转义成回车的意思&#xff0c;所以不需要\\ FileInputStream字节输入流基本用法 -1在ASCII码里面对应的符号&#xff1a; 不…

OpenFeign和Gateway集成Sentinel实现服务降级

目录 OpenFeign集成Sentinel实现fallback服务降级cloud-alibaba-payment8003(支付服务)cloud-common-api(通用模块)cloud-alibaba-order9003(订单服务)Sentinel配置流控规则测试结果 Gateway集成Sentinel实现服务降级cloud-gateway9527(网关)测试结果 总结 OpenFeign集成Sentin…

CS144 - LAB0

CS144 - Lab 0 telnet 发送请求 如图&#xff0c;很简单&#xff0c;但是注意输入时间太久会超时 发邮箱 首先我们需要用命令行去发邮箱&#xff0c;这里我用企业微信邮箱给自己的 qq 邮箱发送~ 整个命令如下&#xff01; 对于其中的参数&#xff0c;其实从英文就可以看出来…

论文浅尝 | 将复杂知识图谱问答对齐为约束代码生成(COLING2025)

笔记整理&#xff1a;康家溱&#xff0c;东南大学在读硕士&#xff0c;研究方向为代码大语言模型 论文链接&#xff1a;https://aclanthology.org/2025.coling-main.267.pdf 发表会议&#xff1a;COLING 2025 1. 动机 近年来&#xff0c;随着大语言模型&#xff08;LLM&#xf…

Golang|分布式搜索引擎中所使用到的设计模式

迭代器模式 定义&#xff1a;在遍历接口时&#xff0c;提供统一的方法函数供调用&#xff0c;保持一致性。核心思想&#xff1a;与大众习惯保持一致&#xff0c;方便第三方实现容器类时保持一致。常见方法&#xff1a;如next()方法&#xff0c;适用于所有集合类&#xff0c;简化…

Ubuntu22.04通过命令行安装qt5

环境&#xff1a; VMware17Pro ubuntu-22.04.5-desktop-amd64.iso 步骤&#xff1a; 安装好虚拟机进入shell&#xff0c;或通过ssh登录&#xff0c;确保虚拟机能上外网&#xff0c;执行命令&#xff1a; sudo apt update sudo apt install build-essential sudo snap in…

STM32:ESP8266 + MQTT 云端与报文全解析

知识点1【MQTT的概述】 1、概述 MQTT是一种基于发布/订阅模式的轻量级应用层协议&#xff0c;运行在TCP/IP协议之上&#xff0c;专用物联网&#xff08;IoT&#xff09;和机器对机器&#xff08;M2M&#xff09;设计&#xff0c;其核心目标是低带宽&#xff0c;高延迟或不稳定…

HTML5 Canvas 星空战机游戏开发全解析

HTML5 Canvas 星空战机游戏开发全解析 一、游戏介绍 这是一款基于HTML5 Canvas开发的2D射击游戏&#xff0c;具有以下特色功能&#xff1a; &#x1f680; 纯代码绘制的星空动态背景✈️ 三种不同特性的敌人类型&#x1f3ae; 键盘控制的玩家战机&#x1f4ca; 完整的分数统…

箱式不确定集

“箱式不确定集&#xff08;Box Uncertainty Set&#xff09;”可以被认为是一种 相对简单但实用的不确定集建模方式。 ✅ 一、什么是“简单的不确定集”&#xff1f; 在鲁棒优化领域&#xff0c;“简单不确定集”通常指的是&#xff1a; 特点描述形式直观数学表达简洁&#…

内存管理 : 04段页结合的实际内存管理

一、课程核心主题引入 这一讲&#xff0c;我要给大家讲的是真正的内存管理&#xff0c;也就是段和页结合在一起的内存管理方式。之前提到过&#xff0c;我们先学习了分段管理内存的工作原理&#xff0c;知道操作系统采用分段的方式&#xff0c;让用户程序能以分段的结构进行编…

vue3: baidusubway using typescript

项目结构&#xff1a; <!--npm install -D tailwindcss-3d BaiduSubwayMap.vue npm install -D tailwindcss postcss autoprefixer--> <template><div class"relative w-full h-screen"><!-- 地图容器 --><div id"subway-container…

Redis最佳实践——性能优化技巧之集群与分片

Redis集群与分片在电商应用中的性能优化技巧 一、Redis集群架构模式解析 1. 主流集群方案对比 方案核心原理适用场景电商应用案例主从复制读写分离数据冗余中小规模读多写少商品详情缓存Redis Sentinel自动故障转移监控高可用需求场景订单状态缓存Redis Cluster原生分布式分片…

常见相机的ISP算法

常见的ISP算法 3A算法 去雾算法 图像增强算法 图像宽动态算法 图像的电子缩放算法&#xff0c;无极电子缩放 图像降噪算法 相机常见问题 1.相机启动速度问题&#xff0c;启动速度较慢 2.相机扛不住高低温问题 3.相机散热问题问题 4.相机高低温芯片保护掉电 5.相机的成像效果或者…

2024 CKA模拟系统制作 | Step-By-Step | 8、题目搭建-创建 Ingress

目录 ​​​​​​免费获取题库配套 CKA_v1.31_模拟系统 一、题目 二、核心考点 Ingress 资源定义 Ingress Controller 依赖 服务暴露验证 网络层次关系 三、搭建模拟环境 1.创建命名空间 2.安装ingress ingress-nginx-controller 3.创建hello.yaml并部署 四、总结 …

OldRoll复古胶片相机:穿越时光,定格经典

在数字摄影盛行的今天&#xff0c;复古胶片相机的独特魅力依然吸引着无数摄影爱好者。OldRoll复古胶片相机这款软件&#xff0c;以其独特的复古风格和丰富的胶片滤镜效果&#xff0c;让用户仿佛穿越回了那个胶片摄影的黄金时代。它不仅模拟了胶片相机的操作界面&#xff0c;还提…