-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.cc
61 lines (45 loc) · 1.21 KB
/
CloneGraph.cc
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "leet.h"
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x): label(x){}
};
#include <algorithm>
#include <cstring>
#include <queue>
#include <map>
class Solution{
public:
UndirectedGraphNode* cloneGraph(UndirectedGraphNode *node) {
if (!node){
return nullptr;
}
std::queue<UndirectedGraphNode*> q;
std::map<int, UndirectedGraphNode*> mp;
int start = node->label;
q.push(node);
mp[start] = new UndirectedGraphNode(start);
while (!q.empty()){
auto now = q.front();
auto nn = mp[now->label];
for (auto &p : now->neighbors){
auto nb = now;
auto iter = mp.find(p->label);
if (iter == mp.end()){
q.push(p);
nb = new UndirectedGraphNode(p->label);
mp[nb->label] = nb;
} else {
nb = iter->second;
}
nn->neighbors.push_back(nb);
}
q.pop();
}
return mp[start];
}
};
int main(){
Solution slu;
return 0;
}