leetcode Clone Graph
来源:互联网 发布:大学生必读书籍 知乎 编辑:程序博客网 时间:2024/05/29 09:34
Clone Graph
Total Accepted: 16482 Total Submissions: 72324My SubmissionsClone 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 #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
Discuss
//首先,这种深拷贝的题目,需要有一个辅助工具来判断中的节点是否重复。本题是图的拷贝,按照某一个规律全部把图的节点全部遍历一遍。
//我是用map来判断是否重复,然后根据原图进行广度优先遍历,然后把新图的节点一一new出来,并对节点进行相应的连接。
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ //7:35->class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { map<UndirectedGraphNode *,UndirectedGraphNode *> repeat; // one set and two queue // store the original nodes and new nodes;que is for old graph. que2 is for new graph. queue<UndirectedGraphNode *> que; queue<UndirectedGraphNode *> que2; UndirectedGraphNode *head=NULL,*h1=NULL,*h2=NULL,*h3=NULL; int i=0,j=0; if(node==NULL) { return head; } que.push(node); h1=head = new UndirectedGraphNode(node->label); que2.push(h1); repeat[node] = h1; // begin bfs while(que.size()>0) { node = que.front(); que.pop(); h1 = que2.front(); que2.pop(); for(i=0;i<node->neighbors.size();i++) { h2 = node->neighbors[i]; if(repeat.count(h2)==0) { h3 = new UndirectedGraphNode(h2->label); h1->neighbors.push_back(h3); repeat[h2] = h3; que.push(h2); que2.push(h3); }else {//add the new link in new graph h1->neighbors.push_back(repeat[h2]); } } } return head; }};
0 0
- LeetCode[Graph]: Clone Graph
- [LeetCode] CLone Graph
- LeetCode:Clone Graph
- [leetcode]Clone Graph
- Leetcode: Clone Graph
- [LeetCode] Clone Graph
- LeetCode题解:Clone Graph
- [LeetCode]Clone Graph
- leetcode Clone Graph
- leetcode-Clone Graph
- LeetCode | Clone Graph
- Leetcode: Clone Graph
- [LeetCode] Clone Graph
- LeetCode OJ:Clone Graph
- Leetcode Clone Graph
- [Leetcode] Clone Graph (Java)
- Clone Graph - LeetCode
- 【leetcode】Clone Graph
- android 背景选择器selector
- Matlab实现迭代法连通区域标记
- 第十三章 13.1.2节练习
- Xamarin.Android之定位
- 设计模式之--单例模式
- leetcode Clone Graph
- oracle主机名修改
- 预处理命令“ # 运算符”和“ ## 运算符” "#@"运算符
- Hibernate 二级缓存的作用
- 今年移动视频广告市场将翻番至15亿美元
- C++通过ODBC连接Oracle数据库
- .net前台截取固定长度超出显示字符
- centos搭建hls 新
- 聊一下我在LINUX环境下用过的C/C++编辑器(或IDE)