问题:Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
思路:图的复制/克隆问题。给你的只是图的冰山一角,就让你拷贝整张图。
第一步,先遍历(两种遍历方法)原图。把所有结点拿到手,构造一个邻接表头。
第二步,根据原图的邻接表头,重建一个新的邻接表头。
第三步,对于每个结点,顺序取得其邻接结点,并将克隆图中对应的结点指针加入到克隆图中对应的邻接表中。
为了访问方便,使用了哈希映射表 unorderd_map<结点label,结点指针> 来重构原图和新图。
代码:时间复杂度O(N),空间复杂度O(N)。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
unordered_map<int, UndirectedGraphNode *> m; //origin graph
queue<UndirectedGraphNode *> q;
q.push(node);
while(!q.empty())
{
UndirectedGraphNode *tmp = q.front();
q.pop();
if(m.find(tmp->label) == m.end())
m.insert(pair<int, UndirectedGraphNode *>(tmp->label, tmp));
for(int i=0;i < tmp->neighbors.size();i++)
if(m.find(tmp->neighbors[i]->label) == m.end())
q.push(tmp->neighbors[i]);
}
unordered_map<int, UndirectedGraphNode *> clone; // clone graph
unordered_map<int, UndirectedGraphNode *>::iterator it = m.begin();
// Step 1: create new node
for(;it != m.end(); it++)
{
UndirectedGraphNode * temp = new UndirectedGraphNode((*it).first);
clone.insert(pair<int, UndirectedGraphNode *>((*it).first, temp));
}
// Step 2: fill the neighbors
it = m.begin();
for(;it != m.end(); it++)
{
for(int i=0;i<(*it).second->neighbors.size();i++)
{
clone[(*it).first]->neighbors.push_back( clone[(*it).second->neighbors[i]->label] );
}
}
return clone[node->label];
}
};