图的深拷贝 Clone Graph
来源:互联网 发布:什么软件可以挣钱 编辑:程序博客网 时间:2024/05/21 22:44
问题:Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
思路:图的复制/克隆问题。给你的只是图的冰山一角,就让你拷贝整张图。
第一步,先遍历(两种遍历方法)原图。把所有结点拿到手,构造一个邻接表头。
第二步,根据原图的邻接表头,重建一个新的邻接表头。
第三步,对于每个结点,顺序取得其邻接结点,并将克隆图中对应的结点指针加入到克隆图中对应的邻接表中。
为了访问方便,使用了哈希映射表 unorderd_map<结点label,结点指针> 来重构原图和新图。
代码:时间复杂度O(N),空间复杂度O(N)。
/** * 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; unordered_map<int, UndirectedGraphNode *> m; //origin graph queue<UndirectedGraphNode *> q; q.push(node); while(!q.empty()) { UndirectedGraphNode *tmp = q.front(); q.pop(); if(m.find(tmp->label) == m.end()) m.insert(pair<int, UndirectedGraphNode *>(tmp->label, tmp)); for(int i=0;i < tmp->neighbors.size();i++) if(m.find(tmp->neighbors[i]->label) == m.end()) q.push(tmp->neighbors[i]); } unordered_map<int, UndirectedGraphNode *> clone; // clone graph unordered_map<int, UndirectedGraphNode *>::iterator it = m.begin(); // Step 1: create new node for(;it != m.end(); it++) { UndirectedGraphNode * temp = new UndirectedGraphNode((*it).first); clone.insert(pair<int, UndirectedGraphNode *>((*it).first, temp)); } // Step 2: fill the neighbors it = m.begin(); for(;it != m.end(); it++) { for(int i=0;i<(*it).second->neighbors.size();i++) { clone[(*it).first]->neighbors.push_back( clone[(*it).second->neighbors[i]->label] ); } } return clone[node->label]; } };
0 0
- 图的深拷贝 Clone Graph
- [C++]LeetCode: 129 Clone Graph (图的深拷贝 BFS && DFS)
- Clone Graph 图的复制 @LeetCode
- Clone Graph DFS&BFS 图的复制
- Clone Graph 克隆图
- clone Graph的总结之一
- Object的clone()方法、深拷贝、浅拷贝
- Object的clone()方法、深拷贝、浅拷贝
- clone的用法--浅拷贝和深拷贝
- Java的clone方法--深拷贝和浅拷贝
- Java clone的浅拷贝及深拷贝 详解
- java Object的clone方法,浅拷贝与深拷贝
- [LeetCode]Clone Graph 克隆图
- leetcode_c++:图:Clone Graph(133)
- 133. Clone Graph 图的复制,运用了BFS
- Clone Graph
- Clone Graph
- Clone Graph
- 题目1178:复数集合
- restlet
- 子数组的最大乘积
- 字符,字符数组,字符指针
- Android资源文件 - 使用资源存储字符串 颜色 尺寸 整型 布尔值 数组
- 图的深拷贝 Clone Graph
- Android-Error记录
- python爱好者
- [20140218]骨骼训练
- Node.js 模块 包
- linux中opt目录
- hdu 3631 Shortest Path(floyd插点法)
- Win7 32位安装Oracle11g R2 图解示例
- tikz画拓扑图