forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamthekorean.py
More file actions
31 lines (25 loc) ยท 1.05 KB
/
samthekorean.py
File metadata and controls
31 lines (25 loc) ยท 1.05 KB
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
27
28
29
30
31
# TC : O(n)
# SC : O(n)
class Solution:
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
if not node:
return None
# Dictionary to store cloned nodes
cloned_nodes = {}
# BFS queue starting with the original node
queue = deque([node])
# Clone the original node
cloned_node = Node(node.val)
cloned_nodes[node] = cloned_node
while queue:
current_node = queue.popleft()
# Iterate through neighbors of the current node
for neighbor in current_node.neighbors:
if neighbor not in cloned_nodes:
# Clone the neighbor and add it to the queue
cloned_neighbor = Node(neighbor.val)
cloned_nodes[neighbor] = cloned_neighbor
queue.append(neighbor)
# Add the cloned neighbor to the cloned current node's neighbors list
cloned_nodes[current_node].neighbors.append(cloned_nodes[neighbor])
return cloned_node