forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyol-han.js
More file actions
37 lines (30 loc) ยท 785 Bytes
/
byol-han.js
File metadata and controls
37 lines (30 loc) ยท 785 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
/**
* https://leetcode.com/problems/clone-graph/
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
* ์๊ฐ ๋ณต์ก๋: O(N) โ ๋
ธ๋ ์๋งํผ ์ํ
* ๊ณต๊ฐ ๋ณต์ก๋: O(N) โ visited ๋งต๊ณผ ์ฌ๊ท ํธ์ถ ์คํ
*/
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
if (!node) return null;
const visited = new Map();
const dfs = (n) => {
if (visited.has(n)) {
return visited.get(n);
}
const clone = new Node(n.val);
visited.set(n, clone);
for (let neighbor of n.neighbors) {
clone.neighbors.push(dfs(neighbor));
}
return clone;
};
return dfs(node);
};