首页 > 其他 > 详细

LeetCode – Refresh – Clone Graph

时间:2015-03-19 06:19:11      阅读:200      评论:0      收藏:0      [点我收藏+]

1. Use BFS to search the graph.

2. Create a hashtable to record the one to one mapping.

 

 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         if (!node) return NULL;
13         unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mapping;
14         UndirectedGraphNode *result = new UndirectedGraphNode(node->label);
15         queue<UndirectedGraphNode *> q;
16         mapping[node] = result;
17         q.push(node);
18         while (!q.empty()) {
19             UndirectedGraphNode *current = q.front();
20             q.pop();
21             for (int i = 0; i < current->neighbors.size(); i++) {
22                 if (mapping.find(current->neighbors[i]) == mapping.end()) {
23                     UndirectedGraphNode *newNode = new UndirectedGraphNode(current->neighbors[i]->label);
24                     q.push(current->neighbors[i]);
25                     mapping[current->neighbors[i]] = newNode;
26                     mapping[current]->neighbors.push_back(newNode);
27                 } else {
28                     mapping[current]->neighbors.push_back(mapping[current->neighbors[i]]);
29                 }
30             }
31         }
32         return result;
33     }
34 };

 

LeetCode – Refresh – Clone Graph

原文:http://www.cnblogs.com/shuashuashua/p/4349266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!