代码改变世界

克隆一个图

2014-11-25 22:34  李涛的技术博客  阅读(139)  评论(0编辑  收藏  举报

克隆一个图结构。

1 struct Node{
2     vector<Node*> neighbors;
3 };

代码如下:

 1 typedef unordered_map<Node*, Node*> Map;
 2 
 3 Node* cloneGraph(Node* graph)
 4 {
 5     if (!graph)
 6         return NULL;
 7 
 8     Map map;
 9     Node* graphCopy = new Node();
10     map[graph] = graphCopy;
11 
12     queue<Node*> q;
13     q.push(graph);
14     while (!q.empty()) {
15         Node* node = q.front();
16         q.pop();
17         int n = node->neighbors.size();
18         for (int i = 0; i < n; i++) {
19             Node* neighbor = node->neighbors[i];
20             if (map.find(neighbor) == map.end()) {
21                 Node* copy = new Node();
22                 map[neighbor] = copy;
23                 map[node]->neighbors.push_back(copy);
24                 q.push(neighbor);
25             } else {
26                 map[node]->neighbors.push_back(map[neighbor]);
27             }
28         }
29         return graphCopy;
30 }