-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloneGraph.js
More file actions
37 lines (29 loc) · 858 Bytes
/
cloneGraph.js
File metadata and controls
37 lines (29 loc) · 858 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
/**
* LeetCode 133. Clone Graph
* https://leetcode.com/problems/clone-graph/
*
* Given a reference of a node in a connected undirected graph, return a deep
* copy (clone) of the graph.
*
* Each node in the graph contains a value (`val`) and a list (`neighbors`) of
* its neighbors.
*/
/**
* @param {{ val: number, neighbors: Array<object> } | null} node
* @return {{ val: number, neighbors: Array<object> } | null}
*/
function cloneGraph(node) {
if (!node) return null;
const map = new Map();
const dfs = (currNode) => {
if (map.has(currNode)) return map.get(currNode);
const copy = { val: currNode.val, neighbors: [] };
map.set(currNode, copy);
for (const neighbor of currNode.neighbors) {
copy.neighbors.push(dfs(neighbor));
}
return copy;
};
return dfs(node);
}
module.exports = { cloneGraph };