-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClone Graph.cpp
31 lines (31 loc) · 1017 Bytes
/
Clone Graph.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
/**
* 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) return NULL;
queue<UndirectedGraphNode *> q;
q.push(node);
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> visited;
visited[node] = new UndirectedGraphNode(node->label);
while (!q.empty()) {
UndirectedGraphNode *f = q.front();
q.pop();
for (int i = 0; i < f->neighbors.size(); ++i) {
UndirectedGraphNode *nb = f->neighbors[i];
if (!visited[nb]) {
visited[nb] = new UndirectedGraphNode(nb->label);
q.push(nb);
}
visited[f]->neighbors.push_back(visited[nb]);
}
}
return visited[node];
}
};