forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoonjonghoo.js
More file actions
36 lines (29 loc) · 725 Bytes
/
moonjonghoo.js
File metadata and controls
36 lines (29 loc) · 725 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
/**
* // Definition for a Node.
* function Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function (node) {
if (!node) return null;
const visited = new Map();
const dfs = (currNode) => {
if (visited.has(currNode)) {
return visited.get(currNode);
}
// 노드 복사
const clone = new Node(currNode.val);
visited.set(currNode, clone);
// 이웃 노드들도 복사해서 연결
for (let neighbor of currNode.neighbors) {
clone.neighbors.push(dfs(neighbor));
}
return clone;
};
return dfs(node);
};