Description
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:
1 | Input: |
Note:
- The number of nodes will be between 1 and 100.
- The undirected graph is a simple graph#Simple_graph), which means no repeated edges and no self-loops in the graph.
- Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
- You must return the copy of the given node as a reference to the cloned graph.
解法
此题的关键在于邻居节点的处理,如果已经复制过一遍了,就不需要进行复制,我们创建一个hashmap来记录已经复制过的节点即可,然后DFS遍历复制整个图,注意,向hashmap中加键值对需发生在递归前,类似于图遍历中的标记操作(标记已经遍历过这个点了),否则会陷入死循环。
具体代码如下:
1 | class Solution { |