File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ # TC : O(n)
2+ # SC : O(n)
3+ class Solution :
4+ def cloneGraph (self , node : Optional ["Node" ]) -> Optional ["Node" ]:
5+ if not node :
6+ return None
7+
8+ # Dictionary to store cloned nodes
9+ cloned_nodes = {}
10+ # BFS queue starting with the original node
11+ queue = deque ([node ])
12+
13+ # Clone the original node
14+ cloned_node = Node (node .val )
15+ cloned_nodes [node ] = cloned_node
16+
17+ while queue :
18+ current_node = queue .popleft ()
19+
20+ # Iterate through neighbors of the current node
21+ for neighbor in current_node .neighbors :
22+ if neighbor not in cloned_nodes :
23+ # Clone the neighbor and add it to the queue
24+ cloned_neighbor = Node (neighbor .val )
25+ cloned_nodes [neighbor ] = cloned_neighbor
26+ queue .append (neighbor )
27+
28+ # Add the cloned neighbor to the cloned current node's neighbors list
29+ cloned_nodes [current_node ].neighbors .append (cloned_nodes [neighbor ])
30+
31+ return cloned_node
You can’t perform that action at this time.
0 commit comments