-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphClone.cpp
More file actions
36 lines (30 loc) · 770 Bytes
/
graphClone.cpp
File metadata and controls
36 lines (30 loc) · 770 Bytes
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
typedef unorder_map<Node *, Node *> Map;
Node *clone(Node *graph)
{
if(!graph) return NULL;
Map map;
queue<Node *> q;
q.push(graph);
Node *graphCopy = new Node();
map[graph] = graphCopy;
while(!q.empty())
{
Node *node = q.front();
q.pop();
int n = node->neighbors.size();
for (int i = 0; i<n; i++)
{
Node *neighbor = node->neighbors[i];
if (map.find(neighbor)==map.end())
{
Node *p = new Node();
map[node]->neighbors.push_back(p);
map[neighbor] = p;
q.push(neighbor);
}else{
map[node]->neighbors.push_back(map[neighbor]);
}
}
}
return graphCopy;
}