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

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

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

给你数组 edges 和整数 nsourcedestination,如果从 sourcedestination 存在 有效路径 ,则返回 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
  • 不存在重复边
  • 不存在指向顶点自身的边

代码:

cpp 复制代码
#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;
}
相关推荐
生信研究猿15 分钟前
leetcode 101.对称二叉树(不会做)
算法·leetcode·职场和发展
重生之我是Java开发战士16 分钟前
【笔试强训】Week1:点击消除,数组中两个字符串的最小距离,dd爱框框,腐烂的苹果,大数乘法
java·开发语言·算法
枫叶林FYL16 分钟前
【自然语言处理 NLP】前沿架构与多模态 选择性状态空间模型与并行扫描算法:从原理到实现
算法·自然语言处理·架构
WolfGang00732126 分钟前
代码随想录算法训练营 Day29 | 动态规划 part02
算法·动态规划
样例过了就是过了27 分钟前
LeetCode热题100 跳跃游戏 II
c++·算法·leetcode·贪心算法·动态规划
rit843249928 分钟前
基于NSGA-II的多目标优化算法(MATLAB实现)
开发语言·算法·matlab
香蕉鼠片28 分钟前
第三大的数
数据结构·算法·leetcode
汀、人工智能29 分钟前
[特殊字符] 第28课:相交链表
数据结构·算法·链表·数据库架构··相交链表
计算机安禾32 分钟前
【数据结构与算法】第32篇:交换排序(一):冒泡排序
c语言·数据结构·c++·算法·链表·排序算法·visual studio code
lxh011335 分钟前
蜗牛排序题解
javascript·算法