Skip to content

Commit bfb932f

Browse files
committed
Add week 9 solutions: cloneGraph
1 parent b139a51 commit bfb932f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

clone-graph/yolophg.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity: O(N + E) Node + Edge
2+
// Space Complexity: O(N + E)
3+
4+
var cloneGraph = function (node) {
5+
// to keep track of all the nodes that have already been copied
6+
const map = new Map();
7+
8+
// helper to perform the deep copy
9+
const dfs = (currentNode) => {
10+
if (!currentNode) return null;
11+
12+
// if the node has already been copied, return the copied one
13+
if (map.has(currentNode)) return map.get(currentNode);
14+
15+
// create a new node with the current node's value
16+
const newNode = new Node(currentNode.val);
17+
18+
// store this new node in the map
19+
map.set(currentNode, newNode);
20+
21+
// iterate through each neighbor of the current node
22+
for (const neighbor of currentNode.neighbors) {
23+
// clone the neighbors and add them to the new node's neighbors
24+
newNode.neighbors.push(dfs(neighbor));
25+
}
26+
27+
// return the newly created node
28+
return newNode;
29+
};
30+
31+
// start the deep copy from the given node
32+
return dfs(node);
33+
};

0 commit comments

Comments
 (0)