码迷,mamicode.com
首页 > 其他好文 > 详细

Clone Graph

时间:2015-11-15 10:49:23      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

 1 /**
 2  * Definition for undirected graph.
 3  * struct UndirectedGraphNode {
 4  *     int label;
 5  *     vector<UndirectedGraphNode *> neighbors;
 6  *     UndirectedGraphNode(int x) : label(x) {};
 7  * };
 8  */
 9 class Solution{
10 public:
11     UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node){
12         unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> record;
13         if(!node)
14             return node;
15         queue<UndirectedGraphNode*> queue;
16         queue.push(node);
17         while(!queue.empty()){
18             UndirectedGraphNode* nextNode = queue.front();
19             queue.pop();
20             if(!record.count(nextNode)){
21                 UndirectedGraphNode* newNode = 
22                     new UndirectedGraphNode(nextNode->label);
23                 record[nextNode] = newNode;
24             }
25             for(int i=0;i<nextNode->neighbors.size();i++){
26                 UndirectedGraphNode* childNode = nextNode->neighbors[i];
27                 if(!record.count(childNode)){
28                     UndirectedGraphNode* newNode = 
29                         new UndirectedGraphNode(childNode->label);
30                     record[childNode] = newNode;
31                     queue.push(childNode);
32                 }
33                 record[nextNode]->neighbors.push_back(record[childNode]);
34             }
35         }
36         return record[node];
37     }
38 };

 

Clone Graph

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4966222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!