每次搜索的时候看这个结点是不是已经被创建,是的话就返回其copy,否则就创建,然后再依次深度遍历其邻居结点并将其加入邻居集合中去
/**
* 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) return NULL;
if(hash.count(node)) return hash[node];
hash[node] = new UndirectedGraphNode(node->label);
for(auto val : node->neighbors)
hash[node]->neighbors.push_back(cloneGraph(val));
return hash[node];
}
private:
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> hash;
};
还有一种解法,这道题和前面一个random list的copy的题类似,关键点是建立一个map存放旧数据结构里的节点和新数据结构里的节点的对应关系。对于这个题,我一开始觉得应该先遍历一遍图,每个节点重建,完善map结构。然后再遍历一遍,把每个节点的neighbors填好。但是其实一遍遍历就可以做完:
/**
* 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) return NULL;
map<UndirectedGraphNode*, UndirectedGraphNode*> m;
queue<UndirectedGraphNode*> q;
q.push(node);
while(!q.empty()){
UndirectedGraphNode *n = q.front();
q.pop();
if(!m[n])
{
UndirectedGraphNode *newnode = new UndirectedGraphNode(n->label);
m[n] = newnode;
}
for(auto a : n->neighbors){
if(!m[a])
{
UndirectedGraphNode *newa = new UndirectedGraphNode(a->label);
m[a] = newa;
q.push(a);
}
m[n]->neighbors.push_back(m[a]);
}
}
return m[node];
}
};