File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 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+ } 
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments