Clone Graph

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (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) {};
* };
*/
typedef UndirectedGraphNode NODE;
typedef pair<NODE*, NODE*> PAIR;
NODE* dfs(NODE *node, unordered_map<NODE*, NODE*> &_map) {
if(_map.count(node)) return _map[node];
NODE *p = new NODE(node->label);
_map.insert(PAIR(node, p));
for(size_t i = 0; i < node->neighbors.size(); ++i) {
p->neighbors.push_back(dfs(node->neighbors[i], _map));
}
return p;
} class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<NODE*, NODE*> _map;
_map[NULL] = NULL;
return dfs(node, _map);
}
};

最新文章

  1. 3、项目资源的提供 - PMO项目管理办公室
  2. jQuery插件 -- Cookie插件jquery.cookie.js(转)
  3. HDU 2243 考研路茫茫——单词情结(AC自动机+矩阵)
  4. 关于TableVIew的上下滚动如何探测其边界
  5. HDU 1316 How Many Fibs?(java,简单题,大数)
  6. java基础知识回顾之接口
  7. npm在项目目录安装插件需要使用sudo
  8. GIT在LINUX下的基本操作
  9. Windows2012中安装PHP-5.6.20+Apache httpd2.4.18+Composer+Laravel+MySQL5.7
  10. 读书笔记_Effective_C++_条款二十四: 若所有参数皆需类型转换,请为此采用non-member函数
  11. Hacker(21)----密码攻防之加密与解密基础
  12. jquery mobile实现拨打电话功能的几种方法
  13. shell初步了解
  14. 怎么查看mysql的安装目录
  15. memcached实战系列(六)理解Memcached的数据存储方式
  16. Python——进程队列
  17. freemarker怎么把数据显示到页面中?
  18. linux下的文本编辑器VI的使用命令
  19. [CLPR] 定位算法探幽 - 边缘和形态学
  20. linux 权限管理命令chmod、文件和目录的权限的意义

热门文章

  1. My Game --简介
  2. linux 2.6.21版本的内核合法的MAC地址
  3. Invoke-WebRequest Invoke-RestMethod 乱码研究
  4. OMG点菜系统
  5. socket协议下如何缓存图片--推荐EGOCache
  6. Hadoop随笔(一):工作流程的源码
  7. bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能
  8. 【转】Flexbox——快速布局神器
  9. netfilter-IPv4实现框架分析(一)
  10. JAVA生成TXT日志文件