/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// write your code here
UndirectedGraphNode *res;
map<int, UndirectedGraphNode*> table;
res = clone(node, table);
return res;
}
//克隆节点
UndirectedGraphNode *clone(UndirectedGraphNode *node, map<int, UndirectedGraphNode*> &table){
if(node == NULL){
return NULL;
}
if(table.find(node->label) != table.end()){
return table[node->label];
}
UndirectedGraphNode *newnode = new UndirectedGraphNode(node->label);
table[node->label] = newnode;
for(int i=0; i<node->neighbors.size(); i++){
UndirectedGraphNode *neighbor = clone(node->neighbors[i], table);
newnode->neighbors.push_back(neighbor);
}
return newnode;
}
};
133. Clone Graph
最新推荐文章于 2020-08-12 10:22:05 发布