forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgwbaik9717.js
More file actions
43 lines (34 loc) · 823 Bytes
/
gwbaik9717.js
File metadata and controls
43 lines (34 loc) · 823 Bytes
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
// v: len(vertexes), e: len(edges)
// Time complexity: O(v + e)
// Space complexity: O(v + e)
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
const nodes = Array.from({ length: 101 }, (_, i) => null);
const dfs = (node) => {
if (!node) {
return;
}
if (nodes[node.val]) {
return nodes[node.val];
}
const newNode = new _Node(node.val);
nodes[node.val] = newNode;
for (const neighbor of node.neighbors) {
const cloned = dfs(neighbor);
newNode.neighbors.push(cloned);
}
return newNode;
};
dfs(node);
return nodes[1];
};