forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone_Graph.cc
37 lines (35 loc) · 1.17 KB
/
Clone_Graph.cc
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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (node == NULL)
return NULL;
UndirectedGraphNode *ret = new UndirectedGraphNode(node->label);
map<UndirectedGraphNode *, UndirectedGraphNode *> mp;
mp[node] = ret;
queue<UndirectedGraphNode *> que;
que.push(node);
UndirectedGraphNode *tmp = NULL, *nxt = NULL;
while (!que.empty()) {
tmp = que.front();
que.pop();
for (int i = 0; i < (tmp->neighbors).size(); i++) {
nxt = (tmp->neighbors)[i];
if (mp.find(nxt) == mp.end()) {
mp[nxt] = new UndirectedGraphNode(nxt->label);
que.push(nxt);
}
(mp[tmp]->neighbors).push_back(mp[nxt]);
}
}
return ret;
}
};