「每日LeetCode」2021年12月5日

本文最后更新于:2023年3月19日 晚上

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

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

image.png
有一个具有 n 个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。
请你确定是否存在从顶点 start 开始,到顶点 end 结束的 有效路径
给你数组 edges 和整数 n、start 和 end,如果从 start 到 end 存在 有效路径 ,则返回 true,否则返回 false 。

示例 1:
输入:n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2 输出:true 解释:存在由顶点 0 到顶点 2 的路径: - 0 → 1 → 2 - 0 → 2
image.png
示例 2:
输入:n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 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 <= start, end <= n - 1
  • 不存在双向边
  • 不存在指向顶点自身的边

思路

哈希表模拟双向图,dfs 遍历判断即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @param {number} n
* @param {number[][]} edges
* @param {number} start
* @param {number} end
* @return {boolean}
*/
var validPath = function (n, edges, start, end) {
const map = new Map();
for (const edge of edges) {
const [start, end] = edge;
if (map.has(start)) {
map.get(start).add(end);
} else {
map.set(start, new Set([end]));
}
if (map.has(end)) {
map.get(end).add(start);
} else {
map.set(end, new Set([start]));
}
}
if (!map.size) return true;
let cur = [...map.get(start)];
const visit = new Set();
const dfs = (arr) => {
if (!arr.length) return false;
const next = new Set();
while (arr.length) {
const cur = arr.pop();
visit.add(cur);
for (const node of [...map.get(cur)]) {
if (!visit.has(node)) next.add(node);
}
if (cur === end) return true;
}
return dfs([...next]);
};
return dfs(cur);
};