bfs
/**
* 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 *> hashmap;
UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
queue<UndirectedGraphNode *> q;
q.push(node);
hashmap[node] = p2;
while(!q.empty()){
UndirectedGraphNode * cur = q.front();
q.pop();
p2 = hashmap[cur];
for(int i = 0; i < cur->neighbors.size(); i++){
UndirectedGraphNode * nb= cur->neighbors[i];
if(hashmap.count(nb)) p2->neighbors.push_back(hashmap[nb]);
else{
UndirectedGraphNode * tmp = new UndirectedGraphNode(nb->label);
hashmap[nb] = tmp;
p2->neighbors.push_back(hashmap[nb]);
q.push(nb);//要注意这里q的元素,是原图中的元素
}
}
}
return hashmap[node];
}
};
dfs
/**
* 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 *> hashmap;
UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
stack<UndirectedGraphNode *> q;
q.push(node);
hashmap[node] = p2;
while(!q.empty()){
UndirectedGraphNode * cur = q.top();
q.pop();
p2 = hashmap[cur];
for(int i = 0; i < cur->neighbors.size(); i++){
UndirectedGraphNode * nb= cur->neighbors[i];
if(hashmap.count(nb)) p2->neighbors.push_back(hashmap[nb]);
else{
UndirectedGraphNode * tmp = new UndirectedGraphNode(nb->label);
hashmap[nb] = tmp;
p2->neighbors.push_back(hashmap[nb]);
q.push(nb);//要注意这里q的元素,是原图中的元素
}
}
}
return hashmap[node];
}
};