博客
关于我
E - 数据结构实验之图论五:从起始点到目标点的最短步数(BFS)
阅读量:764 次
发布时间:2019-03-23

本文共 1667 字,大约阅读时间需要 5 分钟。

在这个问题中,我们需要判断天灾军团是否可以通过现有的通道从n号隘口到达1号隘口,如果可以,我们还需要找出最少需要经过的通道数量。

方法思路

这个问题可以看作是一个图的最短路径问题。具体来说,我们有一个有向图,其中节点表示隘口,边表示通道。我们需要找到从n号隘口到1号隘口的最短路径。如果不存在这样的路径,则输出“NO”。

为了解决这个问题,我们可以使用广度优先搜索(BFS),因为BFS能够在图中找到最短路径。我们从n号隘口开始,逐层搜索,直到到达1号隘口或所有可能的节点都已访问。每次访问一个新节点时,我们记录经过的通道数量,当找到目标节点时返回通道数量。

解决代码

#include 
#include
#include
using namespace std;struct Node { int data; int step; Node(int d, int s) : data(d), step(s) {}};bool BFS(Node start) { queue
q; bool visited[1005] = {false}; q.push(start); visited[start.data] = true; while (!q.empty()) { Node current = q.front(); q.pop(); if (current.data == 1) { return true; } for (int i = 1; i <= n; ++i) { if (!visited[i] && current.step + 1 <= start.step + n) { if (Map[current.data][i]) { visited[i] = true; Node next(i, current.step + 1); q.push(next); } } } } return false;}int main() { ios::sync_with_stdio(false); int n, m; while (true) { cin >> n >> m; if (m == 0) { break; } int a, b; vector
> edges; for (int i = 0; i < m; ++i) { edges.push_back(make_pair(a, b)); } Map[n+1][1] = true; if (BFS(Node(n, 0))) { cout << (current.step + 1) << endl; } else { cout << "NO" << endl; } }}

代码解释

  • 结构体定义:定义了一个Node结构体来存储当前节点的隘口编号和已经过的通道数量。
  • BFS函数:进行广度优先搜索,接受起点,返回是否能到达1号隘口。
  • 输入处理:读取每个测试用例,初始化通道映射关系Map,并调用BFS函数查找最短路径。
  • 输出结果:根据BFS函数的返回值,输出最少通道数量或“NO”。
  • 这个方法确保了在给定的约束条件下,高效地解决问题,并且能够处理大规模输入。

    转载地址:http://soezk.baihongyu.com/

    你可能感兴趣的文章
    nmap指纹识别要点以及又快又准之方法
    查看>>
    Nmap渗透测试指南之指纹识别与探测、伺机而动
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>