File tree Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Expand file tree Collapse file tree 1 file changed +13
-11
lines changed Original file line number Diff line number Diff line change 1+ from collections import deque
12from typing import Optional
3+
24class Solution :
3- def cloneGraph (self , node ) :
5+ def cloneGraph (self , node : Optional [ 'Node' ]) -> Optional [ 'Node' ] :
46 if not node :
57 return None
6- old_to_new = {}
7- def dfs ( n ):
8- if n in old_to_new :
9- return old_to_new [ n ]
10- copy = Node ( n . val )
11- old_to_new [ n ] = copy
12- for neighbor in n . neighbors :
13- copy . neighbors . append (dfs ( neighbor ) )
14- return copy
15- return dfs ( node )
8+ old_to_new = {node : Node ( node . val ) }
9+ queue = deque ([ node ])
10+ while queue :
11+ current = queue . popleft ()
12+ for neighbor in current . neighbors :
13+ if neighbor not in old_to_new :
14+ old_to_new [ neighbor ] = Node ( neighbor . val )
15+ queue . append (neighbor )
16+ old_to_new [ current ]. neighbors . append ( old_to_new [ neighbor ])
17+ return old_to_new [ node ]
You can’t perform that action at this time.
0 commit comments