forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlhc0506.js
More file actions
38 lines (30 loc) · 838 Bytes
/
lhc0506.js
File metadata and controls
38 lines (30 loc) · 838 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
/**
* // 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) {
if (!node) return null;
const stack = [node];
const map = new Map();
map.set(node.val, new _Node(node.val));
while (stack.length > 0) {
const currentNode = stack.pop();
for (const neighbor of currentNode.neighbors) {
if (!map.has(neighbor.val)) {
map.set(neighbor.val, new Node(neighbor.val));
stack.push(neighbor);
}
map.get(currentNode.val).neighbors.push(map.get(neighbor.val));
}
}
return map.get(node.val);
};
// 시간복잡도: O(n)
// 공간복잡도: O(n)