-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclonegraph.cpp
More file actions
43 lines (42 loc) · 1.21 KB
/
clonegraph.cpp
File metadata and controls
43 lines (42 loc) · 1.21 KB
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
/**
* 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 == NULL)
{
return NULL;
}
map<int, UndirectedGraphNode*> m;
queue<UndirectedGraphNode*>q;
q.push(node);
while (!q.empty())
{
auto tmp = q.front();
q.pop();
if (m.count(tmp->label) == 0)
{
auto newnode = new UndirectedGraphNode(tmp->label);
m[tmp->label] = newnode;
}
for (unsigned int i = 0; i < tmp->neighbors.size(); i++)
{
auto nbors = tmp->neighbors[i];
if (m.count(nbors->label) == 0)
{
auto nbnode = new UndirectedGraphNode(nbors->label);
m[nbors->label] = nbnode;
q.push(nbors);
}
m[tmp->label]->neighbors.push_back(m[nbors->label]);
}
}
return m[node->label];
}
};