寻找图中是否存在路径
难度:
标签:
题目描述
有一个具有 n
个顶点的 双向 图,其中每个顶点标记从 0
到 n - 1
(包含 0
和 n - 1
)。图中的边用一个二维整数数组 edges
表示,其中 edges[i] = [ui, vi]
表示顶点 ui
和顶点 vi
之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。
请你确定是否存在从顶点 source
开始,到顶点 destination
结束的 有效路径 。
给你数组 edges
和整数 n
、source
和 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
- 不存在重复边
- 不存在指向顶点自身的边
代码结果
运行时间: 111 ms, 内存: 78.5 MB
/*
* Problem: Given a bidirectional graph represented by an integer n (number of vertices) and an array of edges,
* determine if there exists a valid path from source to destination.
*
* Approach: We can solve this problem using Breadth First Search (BFS) with Java Streams.
* We will use an adjacency list to represent the graph and a boolean array to mark visited nodes.
* Start from the source node, traverse the graph using BFS, and check if we can reach the destination node.
*/
import java.util.*;
import java.util.stream.Collectors;
public class SolutionStream {
public boolean validPath(int n, int[][] edges, int source, int destination) {
// Create adjacency list
Map<Integer, List<Integer>> graph = Arrays.stream(edges)
.collect(Collectors.groupingBy(
edge -> edge[0],
Collectors.mapping(edge -> edge[1], Collectors.toList())
));
Arrays.stream(edges).forEach(edge -> graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]));
// Queue for BFS
Queue<Integer> queue = new LinkedList<>();
queue.offer(source);
// Array to track visited nodes
boolean[] visited = new boolean[n];
visited[source] = true;
// BFS traversal
while (!queue.isEmpty()) {
int node = queue.poll();
if (node == destination) return true;
for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
return false;
}
}
解释
方法:
该题解采用了一种迭代的方法来判断从给定的源点source是否可以到达目标点destination。首先定义一个集合reachable,初始时只包括源点source。然后不断迭代,尝试通过边集edges中的边来扩展reachable集合。在每次迭代中,遍历所有的边,若边的任一顶点已在reachable中,则将另一顶点加入reachable。如果在任意迭代后destination出现在reachable中,则返回true。如果在某次迭代后reachable的大小不再增加,说明所有可达的顶点都已被找到,若此时destination仍未被包含在内,则返回false。
时间复杂度:
O(E * V)
空间复杂度:
O(V)
代码细节讲解
🦆
在你的算法中,是否有处理图中可能存在的环的特殊逻辑,或者算法本身就能有效处理环的存在?
▷🦆
当图中的顶点非常多,但实际边的数量较少时,你的算法效率如何?是否存在更优的方法来处理这种稀疏图?
▷🦆
此算法是否能够处理边中存在重复元素的情况,例如edges数组中包含多个[1, 2],这会影响算法的性能或结果吗?
▷🦆
在算法的迭代过程中,如果source和destination是同一个顶点,即source == destination,该算法是否能立即返回结果?
▷