-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClone_a_graph.cpp
More file actions
44 lines (37 loc) · 1.24 KB
/
Clone_a_graph.cpp
File metadata and controls
44 lines (37 loc) · 1.24 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
44
UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *src)
{
map<UndirectedGraphNode*, UndirectedGraphNode*> m;
queue<UndirectedGraphNode*> q;
// Enqueue src node
q.push(src);
UndirectedGraphNode *node;
// Make a clone Node
node = new UndirectedGraphNode(src->label);
// Put the clone node into the Map
m[src] = node;
while (!q.empty())
{
//Get the front node from the queue
//and then visit all its neighbours
UndirectedGraphNode *u = q.front();
q.pop();
vector<UndirectedGraphNode *> v = u->neighbors;
int n = v.size();
for (int i = 0; i < n; i++)
{
// Check if this node has already been created
if (m[v[i]] == NULL)
{
// If not then create a new Node and
// put into the HashMap
node = new UndirectedGraphNode(v[i]->label);
m[v[i]] = node;
q.push(v[i]);
}
// add these neighbours to the cloned graph node
m[u]->neighbors.push_back(m[v[i]]);
}
}
// Return the address of cloned src Node
return m[src];
}