-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone Graph.cpp
More file actions
38 lines (33 loc) · 1.05 KB
/
Clone Graph.cpp
File metadata and controls
38 lines (33 loc) · 1.05 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
/**
* 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 == nullptr) return nullptr;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map;
queue<UndirectedGraphNode*> bfs;
bfs.push(node);
while(bfs.size()) { //Copy Nodes
auto nextNode = bfs.front(); bfs.pop();
map[nextNode] = new UndirectedGraphNode( nextNode->label );
for(auto vertex: nextNode->neighbors){
if(map.count(vertex) == 0){
bfs.push(vertex);
}
}
}
//Add Edges
for(auto pair : map){
for(auto adj : pair.first->neighbors){
pair.second->neighbors.push_back( map[adj] );
}
}
return map[node];
}
};