-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
43 lines (41 loc) · 1.31 KB
/
solution.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
/**
* 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;
unordered_map<UndirectedGraphNode * , UndirectedGraphNode *> otn;
otn[node] = new UndirectedGraphNode(node -> label);
queue<UndirectedGraphNode *> que;
que.push(node);
while(!que.empty())
{
UndirectedGraphNode* node = que.front() ; que.pop();
int size = node -> neighbors.size();
for(int i = 0 ; i < size ; i ++)
{
if(otn.find(node -> neighbors[i]) == otn.end())
{
UndirectedGraphNode * tmp = new UndirectedGraphNode(node -> neighbors[i] -> label);
otn[node] -> neighbors.push_back(tmp);
otn[node -> neighbors[i]] = tmp;
que.push(node -> neighbors[i]);
}
else
{
otn[node] -> neighbors.push_back(otn[node -> neighbors[i]]);
}
}
}
return otn[node];
}
};