> 文章列表 > Leetcode.1971 寻找图中是否存在路径

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

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

题目链接

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

题目描述

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

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

给你数组 edges和整数 nsourcedestination,如果从 sourcedestination存在 有效路径 ,则返回 true,否则返回 false

示例 1:

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

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

  • 0 → 1 → 2
  • 0 → 2

示例 2:

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

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

提示:

  • 1<=n<=2∗1051 <= n <= 2 * 10^51<=n<=2105
  • 0<=edges.length<=2∗1050 <= edges.length <= 2 * 10^50<=edges.length<=2105
  • edges[i].length==2edges[i].length == 2edges[i].length==2
  • 0<=ui,vi<=n−10 <= ui, vi <= n - 10<=ui,vi<=n1
  • ui≠viui \\neq viui=vi
  • 0<=source,destination<=n−10 <= source, destination <= n - 10<=source,destination<=n1
  • 不存在重复边
  • 不存在指向顶点自身的边

解法:bfs

用一个 布尔数组vis记录访问过的结点,用 bfs 从源点 source开始访问,如果能访问到 destination就返回 true;否则返回 false

时间复杂度: O(n)O(n)O(n)

C++代码:


class Solution {
public:bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {vector<bool> vis(n);vector<vector<int>> g(n);//建图for(auto &e:edges){int a = e[0] , b = e[1];g[a].push_back(b);g[b].push_back(a);}queue<int> q;q.push(source);vis[source] = true;while(!q.empty()){auto t = q.front();q.pop();//如果能访问到终点 返回 trueif(t == destination) return true;for(auto v:g[t]){if(vis[v]) continue;q.push(v);vis[v] = true;}}return false;}
};