您的位置:首页 > 其它

leetcode之Clone Graph

2014-05-28 17:09 246 查看
原题如下:

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


这道题看起来挺复杂的,仍是一个深度复制的问题,问题的关键是在复制一个节点时需要判断其邻居是否已被创建,在此可以采用深度优先搜索DFS,利用unordered_map 来保存已经创建的节点,其中key为节点的label,value为节点,在复制节点时首先判断节点是否为空,为空直接返回空节点(此条件处理一个节点都没有的情况),如果节点在map中,则直接返回map中的节点,否则创建新节点,并将新节点加入map中,接下来按照原节点的neighbor依次递归复制新节点的neighbor,最后返回当前节点。
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<int,UndirectedGraphNode*>mp;
return clone(node,mp);
}
UndirectedGraphNode *clone(UndirectedGraphNode *node,unordered_map<int,UndirectedGraphNode *>&mp){
if(node == NULL)
return node;
if(mp.find(node->label) != mp.end())
return mp[node->label];
UndirectedGraphNode *nNode = new UndirectedGraphNode(node->label);
mp[nNode->label] = nNode;     //
for(int i = 0; i < node->neighbors.size(); i++){
nNode->neighbors.push_back(clone(node->neighbors[i],mp));
}
return nNode;

}
这里用到了unordered_map,它是一个无序的map,其底层实现基于hash算法,所以其查询速度很快,另外,在创建新节点后及时将节点存入了map中,然后才创建其neighbor,我现在有点儿疑惑的是假如只有一个节点,且其neighbor为其自身,这是怎样创建的呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: