Skip to content

Commit 66b6fe1

Browse files
committed
clone-graph solution
1 parent a32ed9d commit 66b6fe1

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

clone-graph/lhc0506.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* // Definition for a _Node.
3+
* function _Node(val, neighbors) {
4+
* this.val = val === undefined ? 0 : val;
5+
* this.neighbors = neighbors === undefined ? [] : neighbors;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {_Node} node
11+
* @return {_Node}
12+
*/
13+
var cloneGraph = function(node) {
14+
if (!node) return null;
15+
16+
const stack = [node];
17+
const map = new Map();
18+
19+
map.set(node.val, new _Node(node.val));
20+
21+
while (stack.length > 0) {
22+
const currentNode = stack.pop();
23+
24+
for (const neighbor of currentNode.neighbors) {
25+
if (!map.has(neighbor.val)) {
26+
map.set(neighbor.val, new Node(neighbor.val));
27+
stack.push(neighbor);
28+
}
29+
map.get(currentNode.val).neighbors.push(map.get(neighbor.val));
30+
}
31+
32+
}
33+
return map.get(node.val);
34+
};
35+
36+
37+
// 시간복잡도: O(n)
38+
// 공간복잡도: O(n)

0 commit comments

Comments
 (0)