-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133. Clone Graph
32 lines (29 loc) · 903 Bytes
/
133. Clone Graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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 nullptr;
map<UndirectedGraphNode *, UndirectedGraphNode *>m;
dfs(node, m);
for(auto it=m.begin(); it!=m.end(); ++it){
for(auto i : it->first->neighbors)
it->second->neighbors.push_back(m[i]);
}
return m[node];
}
void dfs(UndirectedGraphNode *node, map<UndirectedGraphNode *, UndirectedGraphNode *>&m){
if(!node)return;
m[node]= new UndirectedGraphNode(node->label);
for(auto e : node->neighbors){
if(m.find(e)==m.end())
dfs(e, m);
}
}
};