Skip to content

Commit 42a7980

Browse files
committed
💀 [133] kms /////
1 parent 31e7bd3 commit 42a7980

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

133/my_solution.js

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class Node {
2+
constructor(val) {
3+
this.val = val;
4+
this.neighbors = [];
5+
}
6+
}
7+
8+
const buildGraph = (adjList) => {
9+
const nodes = {};
10+
11+
// Create all the nodes
12+
for (let i = 0; i < adjList.length; i++) {
13+
const val = i + 1;
14+
nodes[val] = new Node(val);
15+
}
16+
17+
// Connect the nodes
18+
for (let i = 0; i < adjList.length; i++) {
19+
const node = nodes[i + 1]; // Get the corresponding Node object
20+
21+
for (let j = 0; j < adjList[i].length; j++) {
22+
const neighborVal = adjList[i][j];
23+
const neighborNode = nodes[neighborVal]; // Get the neighbor Node object
24+
node.neighbors.push(neighborNode);
25+
}
26+
}
27+
28+
// Return the reference to the first node (val = 1)
29+
return nodes[1];
30+
}
31+
32+
/**
33+
* @param {Node} node
34+
* @return {Node}
35+
*/
36+
var cloneGraph = function (node) {
37+
if (!node) return node;
38+
let map = new Map();
39+
40+
// closeNode
41+
const dfs = (oldNode) => {
42+
if (map.has(oldNode.val)) {
43+
console.log(map)
44+
console.log("---> node exists:" + oldNode.val)
45+
console.log(oldNode)
46+
return map.get(oldNode.val);
47+
}
48+
49+
let copy = new Node(oldNode.val)
50+
map.set(oldNode.val, copy)
51+
52+
console.log("> map")
53+
console.log(map)
54+
55+
for (let nei of oldNode.neighbors) {
56+
copy.neighbors.push(dfs(nei));
57+
}
58+
59+
return copy;
60+
}
61+
62+
return dfs(node);
63+
};
64+
65+
// let n1= new Node(1, [new Node()])
66+
let node = buildGraph([[2, 4], [1, 3], [2, 4], [1, 3]])
67+
console.log("node")
68+
console.log(node)
69+
cloneGraph(node);

0 commit comments

Comments
 (0)