题目:
题解:
from collections import deque
class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
if not node:
return node
visited = {}
# 将题目给定的节点添加到队列
queue = deque([node])
# 克隆第一个节点并存储到哈希表中
visited[node] = Node(node.val, [])
# 广度优先搜索
while queue:
# 取出队列的头节点
n = queue.popleft()
# 遍历该节点的邻居
for neighbor in n.neighbors:
if neighbor not in visited:
# 如果没有被访问过,就克隆并存储在哈希表中
visited[neighbor] = Node(neighbor.val, [])
# 将邻居节点加入队列中
queue.append(neighbor)
# 更新当前节点的邻居列表
visited[n].neighbors.append(visited[neighbor])
return visited[node]