原题如下:
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 node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
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为其自身,这是怎样创建的呢?