Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int
) and a list (List[Node]
) of its neighbors.
Example:
思路
题目意思很简单,克隆一个无向图。
我们想遍历每一个节点,克隆它的值和neighbors。
使用BFS或DFS遍历,遇到不存在的点就新建。
用一个dict来映射旧点和新点,以便在复制neibours的时候找得到点。
from queue import Queue
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
oldToNew = {}
oldToNew[node] = Node(node.val, [])
q = Queue()
q.put(node)
while not q.empty():
cur = q.get()
cur_copy = oldToNew[cur]
nes_list = []
for ne in cur.neighbors:
if ne not in oldToNew.keys():
ne_copy = Node(ne.val, [])
q.put(ne)
oldToNew[ne] = ne_copy
nes_list.append(oldToNew[ne])
cur_copy.neighbors = nes_list
return oldToNew[node]