-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1971-find-if-path-exists-in-graph(Recursion).js
More file actions
51 lines (42 loc) · 1.16 KB
/
1971-find-if-path-exists-in-graph(Recursion).js
File metadata and controls
51 lines (42 loc) · 1.16 KB
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
41
42
43
44
45
46
47
48
49
50
51
/**
* https://leetcode.com/problems/find-if-path-exists-in-graph/
* @param {number} n
* @param {number[][]} edges
* @param {number} start
* @param {number} end
* @return {boolean}
*/
var validPath = function(n, edges, start, end) {
if (start == end) return true;
const graph = buildGraph(edges);
function hasPath(graph, src, dest, visited) {
if (src == dest) return true;
if (visited.has(start)) return false
visited.add(src);
for(let neighbor of graph[src]) {
if(hasPath(graph, neighbor, dest,visited) === true) {
return true;
}
}
return false;
}
return hasPath(graph, start, end, new Set());
};
const buildGraph = (edges) => {
const graph = {};
for(let edge of edges) {
const [a,b] = edge;
if (!(a in graph)) graph[a] = []
if (!(b in graph)) graph[b] = []
graph[a].push(b);
graph[b].push(a);
}
return graph;
}
// const edges = [
// [0,1],
// [1,2],
// [2,0]
// ];
// console.log(validPath(6, [[0,1],[0,2],[3,5],[5,4],[4,3]], 0, 5));
console.log(validPath(3, [[0,1],[1,2],[2,0]], 0, 2));