-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-056-hasPath.js
78 lines (58 loc) · 1.5 KB
/
structy-056-hasPath.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// https://structy.net/problems/has-path
// p: graph, 2 nodes
// r: boolean
// e:
// dfs recursion
const hasPath = (graph, src, dst) => {
if (src === dst) return true;
for (let neighbor of graph[src]) {
if (hasPath(graph, neighbor, dst)) return true;
}
return false;
};
// // bfs
// const hasPath = (graph, src, dst) => {
// const queue = [src];
// while (queue.length > 0) {
// let current = queue.shift();
// if (current === dst) return true;
// for (let neighbor of graph[current]) {
// queue.push(neighbor);
// }
// }
// return false;
// };
const graph = {
f: ["g", "i"],
g: ["h"],
h: [],
i: ["g", "k"],
j: ["i"],
k: [],
};
console.log(hasPath(graph, "f", "k")); // true
// // dfs recursion
// const hasPath = (graph, src, dst) => {
// if (src === dst) return true;
// for (let neighbor of graph[src]) {
// if (hasPath(graph, neighbor, dst)) return true;
// }
// return false;
// };
// // bfs too complicated
// const hasPath = (graph, src, dst) => {
// const set = new Set();
// const queue = [graph[src]];
// while (queue.length > 0) {
// let current = queue.shift();
// for (let item of current) {
// if (item === dst) return true;
// if (!set.has(item)) {
// queue.push(graph[item]);
// set.add(item);
// }
// }
// console.log(current);
// }
// return false;
// };