-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133.cpp
51 lines (47 loc) · 1.08 KB
/
133.cpp
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
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution
{
public:
Node* cloneGraph(Node* node)
{
if (node == NULL) {
return nullptr;
}
unordered_map<Node*, Node*> mmp;
queue<Node*> q;
q.push(node);
// bfs遍历所有节点,设置对应的新节点
while(!q.empty())
{
auto top = q.front();
q.pop();
auto* nod = new Node();
nod->val = top->val;
mmp[top] = nod;
for (const auto n : top->neighbors) {
if (mmp.find(n) == mmp.end()) {
q.push(n);
}
}
}
for(auto ite = mmp.begin(); ite != mmp.end(); ++ite)
{
for(const auto& n : ite->first->neighbors) {
ite->second->neighbors.push_back(mmp[n]);
}
}
return mmp[node];
}
};