Skip to content

Commit 2df0564

Browse files
committed
Create: 133-Clone-Graph.ts
1 parent a817422 commit 2df0564

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: typescript/133-Clone-Graph.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
let dfs = (node: Node, memo: Map<Node, Node>) => {
2+
if (node === null) return null;
3+
4+
//if this node has already been visited, simply return the counterpart node of the new graph and return
5+
if (memo.has(node)) return memo.get(node);
6+
7+
//node hasn't been already visited, create its counterpart version for the new graph
8+
let newNode = new Node(node.val);
9+
//maps to the old graph counterpart(also marked as visited)
10+
memo.set(node, newNode);
11+
12+
//for each edge of the old node, add that edge in the new graph node
13+
for (let i = 0; i < node.neighbors.length; i++) {
14+
newNode.neighbors.push(dfs(node.neighbors[i], memo));
15+
}
16+
17+
return newNode;
18+
};
19+
20+
function cloneGraph(node: Node | null): Node | null {
21+
//uses a map, maps old graph nodes with new graph ones
22+
//it also tells us which node of the old graph have already been visited
23+
let memo = new Map<Node, Node>();
24+
25+
return dfs(node, memo);
26+
}

0 commit comments

Comments
 (0)