您的位置:首页 > 其它

[LintCode] Clone Graph

2015-10-29 10:55 260 查看

Clone Graph

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
/ \
\_/


SOLUTION:

思路上讲这个题可以分两个部分1,遍历图 2,clone图。

遍历需要用到BFS,基本图的搜索都是BFS,那么也就是要用到queue,先讲node进入队列,然后pop的时候访问他的所有neighbors,把没访问过的neighbor放入队列中,依次pop重复以上操作,在这个过程中将入栈的neighbor存入hashmap中,以便以后确认入栈时是否曾经入队列过,保证只放没遍历过的点入队列。在这个题里,用一个指针+ArrayList模拟一个队列也是没问题的。

clone时,就是要做deep copy。用newnode作为一个map里指向copynode的指针,再次遍历容器里的node,把原来点的neighbors在map里的映射(BFS时候会克隆到)加入新newnode的neighbors里面。

最后return map里的node的映射就可以了

public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null){
return null;
}
//because I need the collection 2 times, so I can't use queue, then I choice ArrayList and a pointer(start)
ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>();
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
nodes.add(node);
map.put(node, new UndirectedGraphNode(node.label));
int start = 0;
//clone nodes
while (start < nodes.size()){
UndirectedGraphNode cur = nodes.get(start++);
for (int i = 0; i < cur.neighbors.size(); i++){
UndirectedGraphNode neighbor = cur.neighbors.get(i);
if (!map.containsKey(neighbor)){
map.put(neighbor, new UndirectedGraphNode(neighbor.label));
nodes.add(neighbor);
}
}
}
// clone neighbors
for (int i = 0; i < nodes.size(); i++){
UndirectedGraphNode newNode = map.get(nodes.get(i));
for (int j = 0; j < nodes.get(i).neighbors.size(); j++){
newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j)));
}
}
return map.get(node);
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: