forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclara-shin.js
More file actions
37 lines (30 loc) Β· 1002 Bytes
/
clara-shin.js
File metadata and controls
37 lines (30 loc) Β· 1002 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
/**
* BFSλ₯Ό μ¬μ©ν κ·Έλν 볡μ
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
if (!node) return null;
// μλ³Έ λ
Έλμ 볡μ λ λ
Έλλ₯Ό λ§€ννλ ν΄μλ§΅
const cloned = new Map();
// BFSλ₯Ό μν ν
const queue = [node];
// μμ λ
Έλ 볡μ
cloned.set(node, new _Node(node.val));
while (queue.length > 0) {
const currentNode = queue.shift();
// νμ¬ λ
Έλμ λͺ¨λ μ΄μλ€μ μ²λ¦¬
for (let neighbor of currentNode.neighbors) {
// μ΄μμ΄ μμ§ λ³΅μ λμ§ μμλ€λ©΄
if (!cloned.has(neighbor)) {
// μλ‘μ΄ λ
Έλ μμ±νκ³ λ§΅μ μ μ₯
cloned.set(neighbor, new _Node(neighbor.val));
// νμ μΆκ°νμ¬ λμ€μ μ²λ¦¬
queue.push(neighbor);
}
// 볡μ λ νμ¬ λ
Έλμ μ΄μ 리μ€νΈμ 볡μ λ μ΄μ μΆκ°
cloned.get(currentNode).neighbors.push(cloned.get(neighbor));
}
}
return cloned.get(node);
};