Skip to content

Commit 40bae91

Browse files
committed
Clone Graph Solution
1 parent 9b6c559 commit 40bae91

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

β€Žclone-graph/clara-shin.jsβ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* BFSλ₯Ό μ‚¬μš©ν•œ κ·Έλž˜ν”„ 볡제
3+
* @param {_Node} node
4+
* @return {_Node}
5+
*/
6+
var cloneGraph = function (node) {
7+
if (!node) return null;
8+
9+
// 원본 λ…Έλ“œμ™€ 볡제된 λ…Έλ“œλ₯Ό λ§€ν•‘ν•˜λŠ” ν•΄μ‹œλ§΅
10+
const cloned = new Map();
11+
12+
// BFSλ₯Ό μœ„ν•œ 큐
13+
const queue = [node];
14+
15+
// μ‹œμž‘ λ…Έλ“œ 볡제
16+
cloned.set(node, new _Node(node.val));
17+
18+
while (queue.length > 0) {
19+
const currentNode = queue.shift();
20+
21+
// ν˜„μž¬ λ…Έλ“œμ˜ λͺ¨λ“  이웃듀을 처리
22+
for (let neighbor of currentNode.neighbors) {
23+
// 이웃이 아직 λ³΅μ œλ˜μ§€ μ•Šμ•˜λ‹€λ©΄
24+
if (!cloned.has(neighbor)) {
25+
// μƒˆλ‘œμš΄ λ…Έλ“œ μƒμ„±ν•˜κ³  맡에 μ €μž₯
26+
cloned.set(neighbor, new _Node(neighbor.val));
27+
// 큐에 μΆ”κ°€ν•˜μ—¬ λ‚˜μ€‘μ— 처리
28+
queue.push(neighbor);
29+
}
30+
31+
// 볡제된 ν˜„μž¬ λ…Έλ“œμ˜ 이웃 λ¦¬μŠ€νŠΈμ— 볡제된 이웃 μΆ”κ°€
32+
cloned.get(currentNode).neighbors.push(cloned.get(neighbor));
33+
}
34+
}
35+
36+
return cloned.get(node);
37+
};

0 commit comments

Comments
Β (0)