首页 > 代码库 > leetcode Clone Graph
leetcode Clone Graph
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出来,并对节点进行相应的连接。
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px;">/**</span>
* 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 {
<span style="white-space:pre"> </span>//add the new link in new graph h1->neighbors.push_back(repeat[h2]); } } } return head; } };
leetcode Clone Graph
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。