21. Clone Graph
2024-10-18 04:37:02
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 #
.
- 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) {};
* };
*/
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);
}
};
最新文章
- 3、项目资源的提供 - PMO项目管理办公室
- jQuery插件 -- Cookie插件jquery.cookie.js(转)
- HDU 2243 考研路茫茫——单词情结(AC自动机+矩阵)
- 关于TableVIew的上下滚动如何探测其边界
- HDU 1316 How Many Fibs?(java,简单题,大数)
- java基础知识回顾之接口
- npm在项目目录安装插件需要使用sudo
- GIT在LINUX下的基本操作
- Windows2012中安装PHP-5.6.20+Apache httpd2.4.18+Composer+Laravel+MySQL5.7
- 读书笔记_Effective_C++_条款二十四: 若所有参数皆需类型转换,请为此采用non-member函数
- Hacker(21)----密码攻防之加密与解密基础
- jquery mobile实现拨打电话功能的几种方法
- shell初步了解
- 怎么查看mysql的安装目录
- memcached实战系列(六)理解Memcached的数据存储方式
- Python——进程队列
- freemarker怎么把数据显示到页面中?
- linux下的文本编辑器VI的使用命令
- [CLPR] 定位算法探幽 - 边缘和形态学
- linux 权限管理命令chmod、文件和目录的权限的意义
热门文章
- My Game --简介
- linux 2.6.21版本的内核合法的MAC地址
- Invoke-WebRequest Invoke-RestMethod 乱码研究
- OMG点菜系统
- socket协议下如何缓存图片--推荐EGOCache
- Hadoop随笔(一):工作流程的源码
- bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能
- 【转】Flexbox——快速布局神器
- netfilter-IPv4实现框架分析(一)
- JAVA生成TXT日志文件