-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.cpp
More file actions
38 lines (38 loc) · 1.19 KB
/
Copy pathCloneGraph.cpp
File metadata and controls
38 lines (38 loc) · 1.19 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) {
// Note: The Solution object is instantiated only once and is reused by each
// test case.
if (!node)
return NULL;
map<UndirectedGraphNode *, UndirectedGraphNode *> node_map;
queue<UndirectedGraphNode *> q;
q.push(node);
node_map[node] = new UndirectedGraphNode(node->label);
while (!q.empty()) {
UndirectedGraphNode *node = q.front();
q.pop();
for (int i = 0; i < node->neighbors.size(); i++) {
if (!node_map.count(node->neighbors[i])) {
node_map[node->neighbors[i]] =
new UndirectedGraphNode(node->neighbors[i]->label);
q.push(node->neighbors[i]);
}
}
}
for (auto iter = node_map.begin(); iter != node_map.end(); iter++) {
for (int i = 0; i < iter->first->neighbors.size(); i++) {
iter->second->neighbors.push_back(node_map[iter->first->neighbors[i]]);
}
}
return node_map[node];
}
};