题目:
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 node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)
return NULL;
queue<UndirectedGraphNode *> q;
unordered_set<UndirectedGraphNode *> iset;
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> table;
q.push(node);
while(!q.empty()) {
UndirectedGraphNode *oldNode = q.front();
q.pop();
//已经处理过,不再扩展
if (iset.find(oldNode) != iset.end())
continue;
iset.insert(oldNode);
for (int i = 0; i < oldNode->neighbors.size(); i++) {
q.push(oldNode->neighbors[i]);
}
}
//创建节点以及构建新旧节点间关系
unordered_set<UndirectedGraphNode *>::iterator it;
for (it = iset.begin(); it != iset.end(); it++) {
UndirectedGraphNode *oldNode = *it;
UndirectedGraphNode *newNode = new UndirectedGraphNode(oldNode->label);
table[oldNode] = newNode;
}
//创建节点与各节点之间的连接
for (it = iset.begin(); it != iset.end(); it++) {
UndirectedGraphNode *oldNode = *it;
UndirectedGraphNode *newNode = table[oldNode];
for (int i = 0; i < oldNode->neighbors.size(); i++) {
(newNode->neighbors).push_back(table[oldNode->neighbors[i]]);
}
}
return table[node];
}
};
本文详细介绍了无向图的克隆算法实现过程,包括序列化与反序列化的概念,以及具体步骤与代码实现。
448

被折叠的 条评论
为什么被折叠?



