-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathClone_Graph.cpp
37 lines (37 loc) · 1.26 KB
/
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
32
33
34
35
36
37
/**
* 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 node;
unordered_map <UndirectedGraphNode*, UndirectedGraphNode*> visited;
UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
visited[node] = newNode;
queue <UndirectedGraphNode*> Q;
Q.push(node);
while(!Q.empty()) {
UndirectedGraphNode *curr = Q.front();
Q.pop();
UndirectedGraphNode *u, *v;
for(int i = 0, n = (int)curr->neighbors.size(); i < n; ++i) {
u = visited[curr];
v = curr->neighbors[i];
if(!visited[v]) {
UndirectedGraphNode *neigh = new UndirectedGraphNode(v->label);
visited[v] = neigh;
u->neighbors.push_back(neigh);
Q.push(v);
} else {
u->neighbors.push_back(visited[v]);
}
}
}
return newNode;
}
};