Skip to content

Commit cee05de

Browse files
Solve ; Clone Graph
1 parent 2201d91 commit cee05de

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

clone-graph/printjin-gmailcom.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1+
from collections import deque
12
from typing import Optional
3+
24
class 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]

0 commit comments

Comments
 (0)