-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_solution.js
69 lines (56 loc) · 1.42 KB
/
my_solution.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
class Node {
constructor(val) {
this.val = val;
this.neighbors = [];
}
}
const buildGraph = (adjList) => {
const nodes = {};
// Create all the nodes
for (let i = 0; i < adjList.length; i++) {
const val = i + 1;
nodes[val] = new Node(val);
}
// Connect the nodes
for (let i = 0; i < adjList.length; i++) {
const node = nodes[i + 1]; // Get the corresponding Node object
for (let j = 0; j < adjList[i].length; j++) {
const neighborVal = adjList[i][j];
const neighborNode = nodes[neighborVal]; // Get the neighbor Node object
node.neighbors.push(neighborNode);
}
}
// Return the reference to the first node (val = 1)
return nodes[1];
}
/**
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function (node) {
if (!node) return node;
let map = new Map();
// closeNode
const dfs = (oldNode) => {
if (map.has(oldNode.val)) {
console.log(map)
console.log("---> node exists:" + oldNode.val)
console.log(oldNode)
return map.get(oldNode.val);
}
let copy = new Node(oldNode.val)
map.set(oldNode.val, copy)
console.log("> map")
console.log(map)
for (let nei of oldNode.neighbors) {
copy.neighbors.push(dfs(nei));
}
return copy;
}
return dfs(node);
};
// let n1= new Node(1, [new Node()])
let node = buildGraph([[2, 4], [1, 3], [2, 4], [1, 3]])
console.log("node")
console.log(node)
cloneGraph(node);