题目:
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.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.
Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Constraints:
- 1 <= Node.val <= 100
- Node.val is unique for each node.
- Number of Nodes will not exceed 100.
- There is no repeated edges and no self-loops in the graph.
- The Graph is connected and all nodes can be visited starting from the given node.
解答:
题目本身的意思比较不容易理解,要求我们复制一个图,对原图进行深拷贝。
其中,深拷贝指的是,对一个节点进行深拷贝,则必须生成一个新的节点,这个节点的所有属性值与原节点相同,但这两个节点在内存中,是两个不同的对象。
所以解题思路为采用深度优先遍历:
- 为避免重复拷贝,建立一个HashMap,使用哈希表来存储原 node 和新 node 的对应关系
- 若 node 节点本身为null,直接返回null
- 遍历 node 的每个邻居节点,若 HashMap中已经存在了对应的邻居节点,则直接获得它的拷贝
- 若 HashMap 中还没存在对应的邻居节点,则递归调用函数进行填充(即将拷贝节点放入Hashmap中,并且使得新 node 的邻接链表添加原 node 的邻接链表里的元素)
具体代码实现如下:
class Solution {
HashMap<Node, Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if(node == null) return null;
Node copy = new Node(node.val, new ArrayList<>());
map.put(node, copy);
for(Node neighbor : node.neighbors){
if(map.containsKey(neighbor)){
copy.neighbors.add(map.get(neighbor));
}else{
copy.neighbors.add(cloneGraph(neighbor));
}
}
return copy;
}
}