Skip to content

Commit 761a237

Browse files
committed
clone graph solution
1 parent 1e9a6bb commit 761a237

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

clone-graph/byol-han.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* https://leetcode.com/problems/clone-graph/
3+
* // Definition for a _Node.
4+
* function _Node(val, neighbors) {
5+
* this.val = val === undefined ? 0 : val;
6+
* this.neighbors = neighbors === undefined ? [] : neighbors;
7+
* };
8+
* 시간 복잡도: O(N) — 노드 수만큼 순회
9+
* 공간 복잡도: O(N) — visited 맵과 재귀 호출 스택
10+
*/
11+
12+
/**
13+
* @param {_Node} node
14+
* @return {_Node}
15+
*/
16+
var cloneGraph = function (node) {
17+
if (!node) return null;
18+
19+
const visited = new Map();
20+
21+
const dfs = (n) => {
22+
if (visited.has(n)) {
23+
return visited.get(n);
24+
}
25+
26+
const clone = new Node(n.val);
27+
visited.set(n, clone);
28+
29+
for (let neighbor of n.neighbors) {
30+
clone.neighbors.push(dfs(neighbor));
31+
}
32+
33+
return clone;
34+
};
35+
36+
return dfs(node);
37+
};

0 commit comments

Comments
 (0)