题目:
Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and,as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2 # 1,2 # 2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
First node is labeled as 0. Connect node0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node1 to node2.
Third node is labeled as 2. Connect node2 to node2(itself), thus forming a self-cycle.
克隆无向图。图中的每个节点都包含一个邻域列表。
OJ的无向图序列化:
节点是唯一标记的。我们使用 # 作为每个节点的分隔符,并用作节点标签和节点的每个邻居的分隔符。例如,序列化图{0,1,2 # 1,2 # 2,2}。
该图共有三个节点,因此包含三个部分,由#分隔。
第一个节点被标记为0。将节点0连接到节点1和2。
第二个节点被标记为1。将节点1连接到节点2。
第三个节点被标记为2。将节点2连接到节点2(本身),从而形成一个自循环。
思路:
考察图的遍历算法, DFS / BFS。
基本思想, 利用一个map数据结构, 在遍历图的过程中, 创建相对应的新的图的部分
import java.util.*;
public class Solution {
private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
return clone(node);
}
private UndirectedGraphNode clone(UndirectedGraphNode node) {
if (node == null)
return null;
if (map.containsKey(node.label))
return map.get(node.label);
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
map.put(clone.label, clone);
for (UndirectedGraphNode neighbor : node.neighbors)
clone.neighbors.add(clone(neighbor));
return clone;
}
}
网友评论