forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0133-clone-graph.ts
26 lines (20 loc) · 944 Bytes
/
0133-clone-graph.ts
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
letdfs=(node: Node,memo: Map<Node,Node>)=>{
if(node===null)returnnull;
//if this node has already been visited, simply return the counterpart node of the new graph and return
if(memo.has(node))returnmemo.get(node);
//node hasn't been already visited, create its counterpart version for the new graph
letnewNode=newNode(node.val);
//maps to the old graph counterpart(also marked as visited)
memo.set(node,newNode);
//for each edge of the old node, add that edge in the new graph node
for(leti=0;i<node.neighbors.length;i++){
newNode.neighbors.push(dfs(node.neighbors[i],memo));
}
returnnewNode;
};
functioncloneGraph(node: Node|null): Node|null{
//uses a map, maps old graph nodes with new graph ones
//it also tells us which node of the old graph have already been visited
letmemo=newMap<Node,Node>();
returndfs(node,memo);
}