Leetcode(133) Clone Graph

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:

img

1
2
3
4
5
6
7
8
Input:
{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}

Explanation:
Node 1's value is 1, and it has two neighbors: Node 2 and 4.
Node 2's value is 2, and it has two neighbors: Node 1 and 3.
Node 3's value is 3, and it has two neighbors: Node 2 and 4.
Node 4's value is 4, and it has two neighbors: Node 1 and 3.

Note:

  1. The number of nodes will be between 1 and 100.
  2. The undirected graph is a simple graph#Simple_graph), which means no repeated edges and no self-loops in the graph.
  3. Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
  4. You must return the copy of the given node as a reference to the cloned graph.

解法

此题的关键在于邻居节点的处理,如果已经复制过一遍了,就不需要进行复制,我们创建一个hashmap来记录已经复制过的节点即可,然后DFS遍历复制整个图,注意,向hashmap中加键值对需发生在递归前,类似于图遍历中的标记操作(标记已经遍历过这个点了),否则会陷入死循环。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
HashMap<Node,Node> copyMap = new HashMap<>();
public Node cloneGraph(Node node) {
if(node == null){
return null;
}
if(!copyMap.containsKey(node)){
List<Node> newNodeNeighbor = new ArrayList<>();
Node newNode = new Node(node.val,newNodeNeighbor);
copyMap.put(node,newNode);
for(int i = 0; i < node.neighbors.size(); i++){
newNodeNeighbor.add(cloneGraph(node.neighbors.get(i)));
}
return newNode;
}
else{
return copyMap.get(node);
}

}
}