LeetCode – Refresh – Clone Graph

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

 

转载于:https://www.cnblogs.com/shuashuashua/p/4349266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值