-
Notifications
You must be signed in to change notification settings - Fork 0
/
157. CloneGraph.cpp
61 lines (53 loc) · 1.34 KB
/
157. 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
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
/***************************************************************************
Class for graph node is as follows:
class graphNode
{
public:
int data;
vector<graphNode *> neighbours;
graphNode()
{
data = 0;
neighbours = vector<graphNode *>();
}
graphNode(int val)
{
data = val;
neighbours = vector<graphNode *>();
}
graphNode(int val, vector<graphNode *> neighbours)
{
data = val;
this->neighbours = neighbours;
}
};
******************************************************************************/
graphNode *cloneGraph(graphNode *node)
{
unordered_map<graphNode *,graphNode *>mp;
// if empty
if(node==NULL)return NULL;
// making a copy of the node and storing it in
// map so that we wont make it again and pushing to queue
queue<graphNode *>q;
graphNode * nn = new graphNode(node->data, {});
mp[node] = nn;
q.push(node);
while(!q.empty()){
auto curr = q.front();
q.pop();
//iterating over nodes
for(auto it: curr->neighbours){
// if i havent made a copy of the node
// then make it
if(mp.find(it)==mp.end()){
mp[it] = new graphNode(it->data, {});
q.push(it);
}
// and upadate the neighbors with curr node
mp[curr]->neighbours.push_back(mp[it]);
}
}
return mp[node];
}