-
Notifications
You must be signed in to change notification settings - Fork 0
/
133.js
39 lines (30 loc) · 884 Bytes
/
133.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
var cloneGraph = function (graph) {
let map = new Map()
const dfs = (node) => {
if (!node) return node;
if (!map.has(node.val)) {
map.set(node.val, new Node(node.val));
map.get(node.val).neighbors = node.neighbors.map((node) => {
return dfs(node)
});
}
return map.get(node.val);
}
return dfs(graph);
}
var cloneGraph = function (node) {
const map = new Map();
const q = [node]
map.set(node, new Node(node.val));
while (q.length) {
const cur = q.shift();
for (const neighbor of cur.neighbors) {
if (!map.has(neighbor)) {
map.set(neighbor, new Node(neighbor.val))
q.push(neighbor);
}
map.get(cur).neighbors.push(map.get(neighbor));
}
}
return map.get(node);
};