-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.cc
More file actions
39 lines (35 loc) · 1.4 KB
/
CloneGraph.cc
File metadata and controls
39 lines (35 loc) · 1.4 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
39
#include <queue>
#include <unordered_map>
#include "leetcode_common/graph"
using namespace std;
namepsace CloneGraph {
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) {
return NULL;
}
unordered_map<leetcode::UndirectedGraphNode *, leetcode::UndirectedGraphNode *> old2newMap;
queue<UndirectedGraphNode *> q;
UndirectedGraphNode * nodeNew = new UndirectedGraphNode(node->label);
old2newMap[node] = nodeNew;
q.push(node);
while (!q.empty()) {
leetcode::UndirectedGraphNode * cur = q.front();
q.pop();
UndirectedGraphNode * curNew = old2newMap[cur];
for (int i = 0; i < cur->neighbors.size(); i++) {
UndirectedGraphNode * neighbor = cur->neighbors[i];
unordered_map<leetcode::UndirectedGraphNode *, leetcode::UndirectedGraphNode *>::iterator it = old2newMap.find(neighbor);
if (it == old2newMap.end()) {
UndirectedGraphNode * neighborNew = new leetcode::UndirectedGraphNode(neighbor->label);
old2newMap[neighbor] = neighborNew;
q.push(neighbor);
}
curNew->neighbors.push_back(old2newMap[neighbor]);
}
}
return nodeNew;
}
};
}