LeetCode 133. Clone Graph
2016-05-05 02:16
429 查看
Clone an undirected graph. Each node in the graph contains a
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
As an example, consider the serialized graph
The graph has a total of three nodes, and therefore contains three parts as separated by
First node is labeled as
Second node is labeled as
Third node is labeled as
Visually, the graph looks like the following:
When comes to graph, usually comes with a mess. Actually graph is not that complicated.
This problem is a good one to dissolve the fear.
labeland 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
#.
First node is labeled as
0. Connect node
0to both nodes
1and
2.
Second node is labeled as
1. Connect node
1to node
2.
Third node is labeled as
2. Connect node
2to node
2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
When comes to graph, usually comes with a mess. Actually graph is not that complicated.
This problem is a good one to dissolve the fear.
// this is to use BFS. UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(!node) return NULL; unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> hashMap; hashMap.insert({node, new UndirectedGraphNode(node->label)}); queue<UndirectedGraphNode*> nodes; nodes.push(node); while(!nodes.empty()) { auto v = nodes.front(); nodes.pop(); for(UndirectedGraphNode* e : v->neighbors) { if(hashMap.find(e) == hashMap.end()) { hashMap.insert({e, new UndirectedGraphNode(e->label)}); nodes.push(e); } (hashMap[v]->neighbors).push_back(hashMap[e]); } } return hashMap[node]; }
相关文章推荐
- 重试C语言之C语言常量
- ecshop dwt模版smarty支持加减乘除运算
- Adobe Photoshop CC 2015安装激活教程
- delete
- delete
- 学习View第二步
- oracle instr函数(oracle 用instr 来代替 like)
- ORACLE中Like与Instr模糊查询性能大比拼(转载)
- PHP POST获取的JSON使用json_decode返回NULL
- CentOS7下利用rsyslog+loganalyzer配置日志服务器及Linux客户端配置
- 58. Length of Last Word
- 最短路径详解
- HDOJ(HDU) 2139 Calculate the formula(水题,又一个用JavaAC不了的题目)
- HDOJ(HDU) 2139 Calculate the formula(水题,又一个用JavaAC不了的题目)
- 第五次作业,向成品进发!
- membership 启用 roleManager 抛出异常:未能加载文件或程序集MySql.Web
- Oracle 特殊字符模糊查询的方法
- oracle中带有特殊符号的模糊查询
- Oracle 模糊查询优化
- Android通知栏学习(基础篇)