Skip to content

Commit b941159

Browse files
committed
clone graph solution
1 parent dd4831a commit b941159

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

clone-graph/krokerdile.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {_Node} node
3+
* @return {_Node}
4+
*/
5+
var cloneGraph = function(node) {
6+
if (!node) return null;
7+
8+
const visited = new Map(); // 원본 노드 -> 복제 노드
9+
10+
function dfs(curr) {
11+
if (visited.has(curr)) {
12+
return visited.get(curr); // 이미 복제한 경우
13+
}
14+
15+
const copy = new _Node(curr.val);
16+
visited.set(curr, copy); // 복제한 노드 저장
17+
18+
for (const neighbor of curr.neighbors) {
19+
copy.neighbors.push(dfs(neighbor)); // 이웃도 재귀적으로 복사
20+
}
21+
22+
return copy;
23+
}
24+
25+
return dfs(node);
26+
};

0 commit comments

Comments
 (0)