-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw-graph-hasPath.js
89 lines (77 loc) · 1.86 KB
/
w-graph-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
79
80
81
82
83
84
85
86
87
88
89
// https://structy.net/problems/has-path
// p: 1 obj, 2 nodes
// r: boolean
// e:
// const graph = {
// f: ['g', 'i'],
// g: ['h'],
// h: [],
// i: ['g', 'k'],
// j: ['i'],
// k: []
// };
// hasPath(graph, 'f', 'k'); // true
// Recursion
const hasPath = (graph, src, dst) => {
if (src === dst) return true;
// if (graph[src].length === 0) {
// console.log(src, false);
// return false;
// }
// console.log(graph[src]);
for (let value of graph[src]) {
if (hasPath(graph, value, dst)) {
return true;
}
}
return false;
// return graph[src].forEach((v) => hasPath(graph, v, dst));
// console.log(false);
};
const graph = {
f: ["g", "i"],
g: ["h"],
h: [],
i: ["g", "k"],
j: ["i"],
k: [],
};
hasPath(graph, "f", "k"); // true
// const graph = {
// f: ["g", "i"],
// g: ["h"],
// h: [],
// i: ["g", "k"],
// j: ["i"],
// k: [],
// };
// hasPath(graph, "f", "j"); // false
// // DFS
// const hasPath = (graph, src, dst) => {
// if (graph[src].length === 0) return false;
// // console.log(graph[src]);
// const stack = [src];
// while (stack.length > 0) {
// const current = stack.pop();
// if (current === dst) return true;
// for (let value of graph[current]) {
// stack.push(value);
// }
// // console.log(graph[current]);
// }
// console.log(false);
// return false;
// };
// // BFS
// const hasPath = (graph, src, dst) => {
// if (graph[src].length === 0) return false;
// const queue = [src];
// while (queue.length > 0) {
// const current = queue.shift();
// if (current === dst) return true;
// for (let value of graph[current]) {
// queue.push(value);
// }
// }
// return false;
// };