当前位置: 首页 > news >正文

1971. 寻找图中是否存在路径

有一个具有 n 个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。

请你确定是否存在从顶点 source 开始,到顶点 destination 结束的 有效路径 。

给你数组 edges 和整数 nsource 和 destination,如果从 source 到 destination 存在 有效路径 ,则返回 true,否则返回 false 。

示例 1:

输入:n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
输出:true
解释:存在由顶点 0 到顶点 2 的路径:
- 0 → 1 → 2 
- 0 → 2

示例 2:

输入:n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
输出:false
解释:不存在由顶点 0 到顶点 5 的路径.

提示:

  • 1 <= n <= 2 * 105
  • 0 <= edges.length <= 2 * 105
  • edges[i].length == 2
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= source, destination <= n - 1
  • 不存在重复边
  • 不存在指向顶点自身的边

代码:

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {vector<vector<int>> adj(n);for (auto& edge : edges) {int x = edge[0];int y = edge[1];adj[x].push_back(y);adj[y].push_back(x);}queue<int> qu;qu.push(source);vector<bool> v(n, false);v[source] = true;while (!qu.empty()) {int ver = qu.front();qu.pop();if (ver == destination) {break;}for (auto next : adj[ver]) {if (!v[next]) {qu.push(next);v[next] = true;}}}return v[destination];}
};
int main() {int n; cin >> n;int col; cin >> col;vector<vector<int>> edges;edges.resize(n);for (auto i = 0; i < n; i++) {edges[i].resize(col);for (auto j = 0; j < col; j++) {cin >> edges[i][j];}}int source; cin >> source;int destination; cin >> destination;Solution solution = Solution();int res = solution.validPath(n, edges, source, destination);cout << res << endl;return 0;
}

http://www.lryc.cn/news/463073.html

相关文章:

  • FLINK SQL语法(1)
  • 【Fargo】1:基于libuv的udp收发程序
  • WebSocket介绍和入门案例
  • k8s集群版本升级
  • XML 和 SimpleXML 简介
  • MySQL 中 LIKE 语句的 `%` 和 `_` 以及 BLOB 和 TEXT 的详细解析和案例示范
  • git clone卡在Receiving objects
  • vue+ant 弹窗可以拖动
  • (42)MATLAB中使用fftshift绘制以零为中心的功率谱
  • Windows本地部署中文羊驼模型(Chinese-Alpaca-Pro-7B)(通俗易懂版)
  • Web3的挑战与机遇:技术发展的现状分析
  • LangGraph - Hierarchical Agent Teams
  • 2021-04-14 proteus中仿真时74HC245三态双向端口扩展输出
  • 解决UNSPSC商品分类的层级不足的方法
  • Pytest基于fixture的参数化及解决乱码问题
  • 使用excel.js(layui-excel)进行layui多级表头导出,根据单元格内容设置背景颜色,并将导出函数添加到toolbar
  • Mysql 5.7 安装与卸载(非常详细)
  • 030 elasticsearch查询、聚合
  • 前端工程启动工具
  • 游戏逆向基础-跳出游戏线程发包
  • 做海外网站需要准备什么
  • 通过OpenCV实现 Lucas-Kanade 算法
  • 7、Vue2(二) vueRouter3+axios+Vuex3
  • 最新PHP礼品卡回收商城 点卡回收系统源码_附教程
  • MySQL数据库和表的基本操作
  • SAM应用:医学图像和视频中的任何内容分割中的基准测试与部署
  • Qt消息对话框
  • FreeRTOS的队列管理
  • 买卖股票的最佳时机(动态规划方法总结)
  • KubeSphere安装mysql8.4.0