标签:
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
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 #.
0. Connect node 0 to both nodes 1 and 2.1. Connect node 1 to node 2.2. Connect node 2 to node 2 (itself), thus forming a self-cycle.Visually, the graph looks like the following:
1
/ / 0 --- 2
/ \_/思路分析:这题考察图的遍历,可以考虑DFS或者BFS对图进行搜索遍历,同时进行图拷贝。下面给出了BFS基于队列的迭代实现解法。比较巧妙的是,需要用到一个HashMap来保存原来的graph的节点和新生成的graph的节点的对应关系,当在原图中BFS遍历当前节点的相邻节点时,要同时在新图对应节点的相邻节点集合中进行相应节点的添加操作。同时这个HashMap的key域还可以当成visited访问标记集合来使用,只添加没有访问过的相邻节点到队列中。每个节点访问一次,时间复杂度和空间复杂度都是O(n).
AC Code
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
//0923
if(node == null) return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); //key old graph node; value new graph node
UndirectedGraphNode newGraphNode = new UndirectedGraphNode(node.label);
newGraphNode.neighbors = new ArrayList<UndirectedGraphNode>();
if(node.neighbors.isEmpty()) return newGraphNode;
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.add(node);
map.put(node, newGraphNode);
while(!queue.isEmpty()){
UndirectedGraphNode curNode = queue.poll();
for(UndirectedGraphNode nnode : curNode.neighbors){
if(!map.containsKey(nnode)){
UndirectedGraphNode copyNode = new UndirectedGraphNode(nnode.label);
map.put(nnode, copyNode);
queue.add(nnode);
}
map.get(curNode).neighbors.add(map.get(nnode));
}
}
return newGraphNode;
}
}标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/44726023