133. Clone Graph
solution
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if not node:
return node
node_dict = {}
node_dict[node.val] = Node(node.val) # 遍历copy时,快速定位已有Node, 用于neighbor关系。顺便记录了已遍历过的
queue = collections.deque([node])
while queue:
cur = queue.popleft() # 注意这里不能和node重名, 用于最后输出
for neighbour in cur.neighbors:
if neighbour.val not in node_dict:
node_dict[neighbour.val] = Node(neighbour.val)
queue.append(neighbour) # 注意: 放在if里避免了重复遍历相同,因此没有创建额外的visited
# 这里每次append, 而不是一个层之后 neighbor=clone_neighbor
node_dict[cur.val].neighbors.append(node_dict[neighbour.val])
return node_dict[node.val]follow up
Last updated