Leetcode-133. Clone Graph
来源:互联网 发布:取名软件免费版 编辑:程序博客网 时间:2024/06/03 10:01
133. Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.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 0 to both nodes 1 and 2.Second node is labeled as 1. Connect node 1 to node 2.Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
目标:克隆一个无向图,其中,图的节点由以下结构表示。
- Definition for undirected graph.
- struct UndirectedGraphNode {
- int label;
- vector
<UndirectedGraphNode *>
neighbors; - UndirectedGraphNode(int x) : label(x) {};
};
在solution里添加一个
map<UndirectedGraphNode *, UndirectedGraphNode *> m
来保存克隆图(Key 为节点,Value 为该节点的邻接节点)。用DFS算法遍历全图,若当前节点已在克隆图中,则返回克隆图中的该节点,否则创立新节点加入克隆图中,并添加其所有邻接节点。
class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(!node) return NULL; if(m.count(node)) return m[node]; UndirectedGraphNode *nodeClone = new UndirectedGraphNode(node->label); m[node] = nodeClone; for(int i=0;i<node->neighbors.size();i++) { UndirectedGraphNode *temp = cloneGraph(node->neighbors[i]); if(temp != NULL) nodeClone->neighbors.push_back(temp); } return nodeClone; } private: map<UndirectedGraphNode *, UndirectedGraphNode *> m; };
0 0
- LeetCode 133. Clone Graph
- [Leetcode] 133. Clone Graph
- [leetcode] 133.Clone Graph
- Leetcode 133. Clone Graph
- 133. Clone Graph LeetCode
- LeetCode 133. Clone Graph
- leetcode 133. Clone Graph
- LeetCode *** 133. Clone Graph
- leetcode-133. Clone Graph
- LeetCode 133. Clone Graph
- [LeetCode] 133. Clone Graph
- LeetCode: 133. Clone Graph
- Leetcode-133. Clone Graph
- Leetcode 133. Clone Graph
- LeetCode 133. Clone Graph
- leetcode 133. Clone Graph
- [LeetCode]133. Clone Graph
- 【leetcode】133. Clone Graph
- 【codeforce】几何
- c#基础--数据类型及变换
- VS2013中对多字节字符集支持的方法:下载 Multibyte MFC Library for Visual Studio 2013
- linux基础unit1
- iOS推送实现/ 服务器向iOS APP推送消息
- Leetcode-133. Clone Graph
- Android之二维码生成与扫描
- MYSQL基础1
- iOS UITableViewCell点击效果,点击后消失
- 1052 (未完成)
- PHP 亚洲常用时区编码
- ARPSpoofing、arp欺骗性攻击、arpspoof源码分析
- Auto install opencv after installing Ubuntu
- Android 数据库框架ormlite 使用精要