-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathCloneGraph.cpp
50 lines (40 loc) · 1.17 KB
/
CloneGraph.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
/*
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
LINK: https://www.interviewbit.com/problems/clone-graph/
*/
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node)
{
if(node == NULL)
return node;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
queue<UndirectedGraphNode*> q;
UndirectedGraphNode* src = new UndirectedGraphNode(node->label);
mp[node] = src;
q.push(node);
while(!q.empty())
{
UndirectedGraphNode* u = q.front();
q.pop();
vector<UndirectedGraphNode*> v = u->neighbors;
int n = v.size();
for(int i=0;i<n;i++)
{
if(mp[v[i]] == NULL)
{
UndirectedGraphNode* temp = new UndirectedGraphNode(v[i]->label);
mp[v[i]] = temp;
q.push(v[i]);
}
mp[u]->neighbors.push_back(mp[v[i]]);
}
}
return src;
}