[LeetCode]Clone Graph
2016-04-17 21:32
381 查看
Clone an undirected graph. Each node in the graph contains a
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
a separator for node label and each neighbor of the node.
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
both nodes
Second node is labeled as
node
Third node is labeled as
node
Visually, the graph looks like the following:
BFS,用hash来存储新的图和旧图的一一对应关系的点,采用BFS搜索。然后对每一个点存相邻点。
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 / \ \_/
BFS,用hash来存储新的图和旧图的一一对应关系的点,采用BFS搜索。然后对每一个点存相邻点。
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { unordered_map<UndirectedGraphNode * ,UndirectedGraphNode *> NodeMap; //和克隆图之间的Map这样可以一次遍历完 queue<UndirectedGraphNode *> Qq; if(node == NULL) return node; Qq.push(node); while(!Qq.empty()){ UndirectedGraphNode *top = Qq.front(); Qq.pop(); if(NodeMap.count(top)==0){//没有节点 UndirectedGraphNode * Temp = new UndirectedGraphNode(top->label); NodeMap[top] = Temp; } //保存相邻节点 for(auto it = top->neighbors.begin(); it!=top->neighbors.end(); ++it){ UndirectedGraphNode *adj = *it; if(NodeMap.count(adj)==0){//没有该节点,创建节点,同时间也避免了环,之前遍历过的节点不会再遍历 UndirectedGraphNode *Temp = new UndirectedGraphNode(adj->label); NodeMap[adj] = Temp; Qq.push(adj); } NodeMap[top]->neighbors.push_back(NodeMap[adj]); //给定字节点所有链接节点,如果有环也会保留,因为没有入队列 } } return NodeMap[node]; } };
相关文章推荐
- json-lib 的maven dependency
- 如何判断一个类是否支持某属性和方法以及如何判断IOS的版本
- 算法导论 思考题 2-4
- Hadoop教程(五)Hadoop分布式集群部署安装
- 手机平板要兼顾,探究碎片
- 9.1 JavaScritp:为数据带来生命-对象中的对象
- bzoj 1832 lca
- 关于http
- django 文件上传 研究
- SQL Server数据库基础(一),数据库表、时间、创建约束
- ios开发中归档的使用
- JavaBean技术
- warning : incompatible implicit declaration of built-in function 'exit' [enabled by default]
- 笔试题28. LeetCode OJ (15)
- 在Ubuntu14.04上部署使用SMART HTTP的Git服务器
- LintCode : Binary Tree Path Sum
- linux网络命令
- 深入Java集合学习系列:HashMap的实现原理--转
- 计蒜客 挑战难题 X的平方根
- 【Leetcode】:169. Majority Element 问题 in Go语言