Skip to content

Commit 1c45c71

Browse files
committed
solve : clone graph
1 parent 1127387 commit 1c45c71

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

clone-graph/samthekorean.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

0 commit comments

Comments
 (0)