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] = Nod