Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2df0564

Browse files
committed
Create: 133-Clone-Graph.ts
1 parenta817422 commit2df0564

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎typescript/133-Clone-Graph.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
letdfs=(node:Node,memo:Map<Node,Node>)=>{
2+
if(node===null)returnnull;
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))returnmemo.get(node);
6+
7+
//node hasn't been already visited, create its counterpart version for the new graph
8+
letnewNode=newNode(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(leti=0;i<node.neighbors.length;i++){
14+
newNode.neighbors.push(dfs(node.neighbors[i],memo));
15+
}
16+
17+
returnnewNode;
18+
};
19+
20+
functioncloneGraph(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+
letmemo=newMap<Node,Node>();
24+
25+
returndfs(node,memo);
26+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp