博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode】Clone Graph
阅读量:5213 次
发布时间:2019-06-14

本文共 1780 字,大约阅读时间需要 5 分钟。

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:

Nodes are labeled uniquely.

We use 
# as a separator for each node, and 
, as a separator for node label and each neighbor of the node.

 

As an example, consider the serialized graph {

0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

 

Visually, the graph looks like the following:

1      / \     /   \    0 --- 2         / \         \_/
1 /** 2  * Definition for undirected graph. 3  * struct UndirectedGraphNode { 4  *     int label; 5  *     vector
neighbors; 6 * UndirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution {10 public:11 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {12 unordered_map
map;13 if (node == nullptr) {14 return nullptr;15 }16 return clone(node, map);17 }18 private:19 UndirectedGraphNode *clone(UndirectedGraphNode *node, 20 unordered_map
&map) {21 if (map.find(node) != map.end()) {22 return map[node];23 } 24 UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);25 map[node] = new_node;26 for (auto n : node->neighbors) {27 new_node->neighbors.push_back(clone(n, map));28 }29 return new_node;30 }31 };
View Code

借助hash表

转载于:https://www.cnblogs.com/dengeven/p/3766447.html

你可能感兴趣的文章
设计模式课程 设计模式精讲 2-2 UML类图讲解
查看>>
为块级元素添加链接
查看>>
Silverlight 的菜单控件。(不是 Toolkit的)
查看>>
:hover 鼠标同时触发两个元素变化
查看>>
go语言学习十三 - 相等性
查看>>
python生成可执行exe文件
查看>>
Idea 提交代码到码云(提交到github也大同小异)
查看>>
c#连接excel2007未安装ISAM解决
查看>>
Mono 异步加载数据更新主线程
查看>>
初识lua
查看>>
我是插件狂人,jDuang,jValidator,jModal,jGallery
查看>>
张季跃 201771010139《面向对象程序设计(java)》第四周学习总结
查看>>
如何解除循环引用
查看>>
android中fragment的使用及与activity之间的通信
查看>>
字典【Tire 模板】
查看>>
[IOI2014] 假期
查看>>
ListView滑动删除 ,仿腾讯QQ
查看>>
[NOI 2016]优秀的拆分
查看>>
大学时代的DOS回忆
查看>>
SQL: See the TSQL underneath the sp_execute calls
查看>>