-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (46 loc) · 1.22 KB
/
index.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
/**
* Valid graph tree
*
* @author David Lacedonia <[email protected]>
*
* @param {number} n
* @param {number[][]} edges
*
* @return {boolean}
*/
function validGraphTree(n, edges) {
const adjacencyList = createAdjacencyList(n, edges);
let seen = { 0: true };
let stack = [0];
while (stack.length) {
const node = stack.pop();
for (let neighbour of adjacencyList[node] || []) {
if (seen[neighbour]) {
return false;
}
stack.push(neighbour);
seen[neighbour] = true;
// remove actual node from neighbour, to prevent revisiting on undirected graphs
adjacencyList[neighbour] = adjacencyList[neighbour].filter(
(i) => i !== node
);
}
}
return Object.keys(seen).length === n;
}
/**
* Adjacenct list
*
* List of sub-lists
* where each sub-list is the list of the immediate neighbours for the i'th node
*/
const createAdjacencyList = (n, edges) => {
let list = [];
for (let edge of edges) {
const [x, y] = edge;
list[x] = [...(list[x] || []), y];
list[y] = [...(list[y] || []), x];
}
return list;
};
export default validGraphTree;