Clone Graph
来源:互联网 发布:网络用语dbp是什么意思 编辑:程序博客网 时间:2024/05/02 00:51
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 #
.
- 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 / \ \_/
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(node==NULL) { return NULL; } map<int, UndirectedGraphNode*> nodes; queue<UndirectedGraphNode*> q; q.push(node); while(!q.empty()) { UndirectedGraphNode* tmp = q.front(); q.pop(); if(nodes.find(tmp->label)==nodes.end()) { UndirectedGraphNode* new_node = new UndirectedGraphNode(tmp->label); nodes[new_node->label] = new_node; for(int i=0;i<tmp->neighbors.size();i++) { q.push(tmp->neighbors[i]); } } } q.push(node); while(!q.empty()) { UndirectedGraphNode* tmp = q.front(); q.pop(); UndirectedGraphNode* existingnode = nodes[tmp->label]; if(existingnode->neighbors.empty()&&!tmp->neighbors.empty()) { for(int i=0;i<tmp->neighbors.size();i++) { existingnode->neighbors.push_back(nodes[tmp->neighbors[i]->label]); q.push(tmp->neighbors[i]); } } } return nodes[node->label]; }};
0 0
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- oracle创建dblink详细步骤
- 帝国自定义列表模版使用方法
- Binary XML file line # : Error inflating class
- 我在网络上看到的PDM的概念、定义、优缺点等相关信息
- ViewFlipper动态加载View
- Clone Graph
- 天球坐标系的相关基础知识
- 常用的OpenCV函数速查
- mysql replace语句使用
- IOS基础之设置APP的名字、设置图标、添加等待加载时的图片
- 嵌入式Linux内核I2C子系统详解
- python面向对象-理清object与type的关系
- uwsgi安装使用
- NSString的多个URL字符串的分割和截取技巧