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

LeetCode – Refresh – Clone Graph

时间:2015-03-19 06:19:16      阅读:125      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!