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 
12     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<UndirectedGraphNode *, UndirectedGraphNode*> &dict) {
13         if (node == NULL) return NULL;
14         UndirectedGraphNode *result = new UndirectedGraphNode(node->label);
15         dict[node] = result;
16         
17         for (int i = 0; i < node->neighbors.size(); i++){
18             
19             if (dict.find(node->neighbors[i]) == dict.end()) {
20                 
21                 UndirectedGraphNode *tmp = cloneGraph(node->neighbors[i], dict);
22                 result->neighbors.push_back(tmp);
23             }
24             else result->neighbors.push_back(dict[node->neighbors[i]]);
25         }
26         return result;
27     }
28     
29     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
30         
31         if (node == NULL) return NULL;
32         unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> dict;
33         return cloneGraph(node, dict);
34     }
35 };

 

posted on 2013-10-28 01:21  tanghulu321  阅读(183)  评论(0编辑  收藏  举报