Skip to content

Commit 341a991

Browse files
committedMay 22, 2025
clone-graph solution
·
v4.15.0v4.8.0
1 parent 5a2c870 commit 341a991

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎clone-graph/moonjonghoo.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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 visited = new Map();
17+
18+
const dfs = (currNode) => {
19+
if (visited.has(currNode)) {
20+
return visited.get(currNode);
21+
}
22+
23+
// 노드 복사
24+
const clone = new Node(currNode.val);
25+
visited.set(currNode, clone);
26+
27+
// 이웃 노드들도 복사해서 연결
28+
for (let neighbor of currNode.neighbors) {
29+
clone.neighbors.push(dfs(neighbor));
30+
}
31+
32+
return clone;
33+
};
34+
35+
return dfs(node);
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.