问题描述:
/**
* Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
*
* 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 node 0 to both nodes 1 and 2.
* Second node is labeled as 1. Connect node 1 to node 2.
* Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
* Visually, the graph looks like the following:
*
* 1
* / \
* / \
* 0 --- 2
* / \
* \_/
*/
有一个无向图,每个节点包含两部分信息,1、节点的值,2、节点的邻居。现在要把这个无向图复制一下。
思路就是用一个队列queue来存储图没有访问的节点,hashset集合visited来存储访问过的节点,map来存储复制的节点。每次从queue弹出要访问的节点,然后复制到map当中,然后再处理这个节点的邻居。当然在每次访问节点时都要判断此节点是否被访问过,是否被复制过。代码如下:
public static UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null)
return node;
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();//队列存放没有访问过的节点
queue.add(node);
Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();// hashset集合visited存放访问过的节点
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();//map来存储复制的节点
while (!queue.isEmpty()) {
UndirectedGraphNode n = queue.remove();//从队列里弹出要访问的图节点
if (visited.contains(n))// 如果visited有这个节点则代表访问过,进行下一次循环
continue;
visited.add(n);
UndirectedGraphNode clone;//克隆图的副本
if (!map.containsKey(n)) {//如果map里面没有这个节点则表明这个节点没有被访问过,然后将这个节点克隆给clone
clone = new UndirectedGraphNode(n.label);
map.put(n, clone);
} else {
clone = map.get(n);
}
for (UndirectedGraphNode child : n.neighbors) {//处理节点的邻居,维护节点之间的关系
queue.add(child);
UndirectedGraphNode cloneChild;
if (!map.containsKey(child)) {
cloneChild = new UndirectedGraphNode(child.label);
map.put(child, cloneChild);
} else {
cloneChild = map.get(child);
}
clone.neighbors.add(cloneChild);
}
}
return map.get(node);
}
图的节点结构:
public class UndirectedGraphNode {
public int label;
public List<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int label){
this.label=label;
neighbors = new ArrayList<UndirectedGraphNode>();
}
}
初始化图:
UndirectedGraphNode n0=new UndirectedGraphNode(0);
UndirectedGraphNode n1=new UndirectedGraphNode(1);
UndirectedGraphNode n2=new UndirectedGraphNode(2);
n0.neighbors.add(n1);
n0.neighbors.add(n2);
n1.neighbors.add(n0);
n1.neighbors.add(n2);
n2.neighbors.add(n2);