Clone Graph

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 };

 

posted @ 2015-11-15 10:36  wxquare  阅读(151)  评论(0编辑  收藏  举报