-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-057-undirectedPath.js
122 lines (92 loc) · 2.53 KB
/
structy-057-undirectedPath.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// https://structy.net/problems/undirected-path
// p: arr of edges, 2 nodes
// r: boolean
// dfs: recursion
const buildGraph = (edges) => {
const graph = {};
for (let edge of edges) {
const [a, b] = edge;
!(a in graph) && (graph[a] = []);
!(b in graph) && (graph[b] = []);
graph[a].push(b);
graph[b].push(a);
}
return graph;
};
// dfs recursion 2
const undirectedPath = (edges, nodeA, nodeB) => {
const graph = buildGraph(edges);
const visited = new Set();
return findPath(graph, nodeA, nodeB, visited);
};
const findPath = (graph, start, end, visited) => {
if (start === end) return true;
for (let neighbor of graph[start]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
if (findPath(graph, neighbor, end, visited)) return true;
}
}
return false;
};
const edges = [
["i", "j"],
["k", "i"],
["m", "k"],
["k", "l"],
["o", "n"],
];
// // dfs recursion 1
// const undirectedPath = (edges, nodeA, nodeB, set = new Set()) => {
// const graph = buildGraph(edges);
// if (nodeA === nodeB) return true;
// for (let neighbor of graph[nodeA]) {
// console.log(neighbor);
// if (!set.has(neighbor)) {
// set.add(neighbor);
// if (undirectedPath(edges, neighbor, nodeB, set)) return true;
// }
// }
// return false;
// };
// {
// i: [ 'j', 'k' ],
// j: [ 'i' ],
// k: [ 'i', 'm', 'l' ],
// m: [ 'k' ],
// l: [ 'k' ],
// o: [ 'n' ],
// n: [ 'o' ]
// }
// console.log(undirectedPath(edges, "j", "m")); // -> true
console.log(undirectedPath(edges, "k", "o")); // -> false
// const buildGraph = (edges) => {
// const graph = {};
// // convert to graph:
// for (let edge of edges) {
// const [a, b] = edge;
// !(a in graph) && (graph[a] = []);
// !(b in graph) && (graph[b] = []);
// graph[a].push(b);
// graph[b].push(a);
// }
// return graph;
// };
// // bfs
// const undirectedPath = (edges, nodeA, nodeB) => {
// const graph = buildGraph(edges);
// const queue = [nodeA];
// const set = new Set();
// while (queue.length > 0) {
// const current = queue.shift();
// for (let node of graph[current]) {
// console.log(node);
// if (node === nodeB) return true;
// if (!set.has(node)) {
// queue.push(node);
// set.add(node);
// }
// }
// }
// return false;
// };