题目如下:实现克隆图的算法 题目链接
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
/ \
\_/
分析:BFS或者DFS遍历图,遍历的过程中复制节点,用哈希表保存新建立的节点的地址(同时这个哈希表可以用做节点访问标志)代码如下: 本文地址
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
typedef unordered_map<int, UndirectedGraphNode *> Map;
if(node == NULL)return NULL;
Map gmap;//保存克隆图的节点的地址,顺便作为节点是否访问的标记
stack<UndirectedGraphNode *>gstack;
UndirectedGraphNode *res = new UndirectedGraphNode(node->label);
gmap.insert(Map::value_type(res->label, res));
gstack.push(node);
while(gstack.empty() == false)
{
UndirectedGraphNode *p = gstack.top(), *newp;
gstack.pop();
if(gmap.find(p->label) != gmap.end())//查找克隆图节点是否已经构造
newp = gmap[p->label];
else
{
newp = new UndirectedGraphNode(p->label);
gmap.insert(Map::value_type(p->label, newp));
}
for(int i = ; i < p->neighbors.size(); i++)
{
UndirectedGraphNode *tmp = p->neighbors[i];
if(gmap.find(tmp->label) == gmap.end())
{
gmap.insert(Map::value_type(tmp->label,
new UndirectedGraphNode(tmp->label)));
gstack.push(tmp);
}
//设置克隆图节点的邻接点
newp->neighbors.push_back(gmap[tmp->label]);
}
}
return res;
}
};
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3418412.html