【题目描述】
Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.
How we serialize an undirected graph:
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#.
1.First node is labeled as0. Connect node0to both nodes1and2.
2.Second node is labeled as1. Connect node1to node2.
3.Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
克隆一张无向图,图中的每个节点包含一个label和一个列表neighbors。
数据中如何表示一个无向图?http://www.lintcode.com/help/graph/
你的程序需要返回一个经过深度拷贝的新图。这个新图和原图具有同样的结构,并且对新图的任何改动不会对原图造成任何影响。
样例
比如,序列化图{0,1,2#1,2#2,2}共有三个节点, 因此包含两个个分隔符#。
1.第一个节点label为0,存在边从节点0链接到节点1和节点2
2.第二个节点label为1,存在边从节点1连接到节点2
3.第三个节点label为2,存在边从节点2连接到节点2(本身),从而形成自环。
我们能看到如下的图:
1
/ \
/ \
0 --- 2
/ \
\_/
【题目链接】
www.lintcode.com/en/problem/clone-graph/
【题目解析】
这道题考察的是对图的遍历和利用HashMap拷贝的方法。
对图的遍历就是两个经典的方法DFS和BFS。BFS经常用Queue实现,DFS经常用递归实现(可改为栈实现)。
拷贝方法是用用HashMap,key存原始值,value存copy的值,用DFS,BFS方法遍历帮助拷贝neighbors的值。
【参考答案】