博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
133. Clone Graph
阅读量:6717 次
发布时间:2019-06-25

本文共 2358 字,大约阅读时间需要 7 分钟。

133. 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 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.Visually, the graph looks like the following:       1      / \     /   \    0 --- 2         / \         \_/

解析

  • 考察图的基本遍历方法,DFS/BFS
  • 注意细节bug
  • 运用unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> hash进行图的映射关系存储
// clone graphclass Solution_133 {// date 2017/12/29 10:01// date 2017/12/29 11:04public:    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {         unordered_map
hash; if (!node) { return node; } if (hash.find(node)!=hash.end()) //找到,关键字已经访问过 { hash[node] = new UndirectedGraphNode(node->label); for (auto iter: node->neighbors) { hash[node]->neighbors.push_back(cloneGraph(iter)); //递归DFS //超时 } } return hash[node]; } UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) //BFS { if (!node) { return node; } unordered_map
hash; UndirectedGraphNode* head = new UndirectedGraphNode(node->label); hash[node] = head; queue
que; que.push(node); //que.push(head); bug 花费1小时查找 while (!que.empty()) { UndirectedGraphNode* q = que.front(); que.pop(); for (auto iter: q->neighbors) { if (!hash[iter]) //还没有访问 { UndirectedGraphNode* temp = new UndirectedGraphNode(iter->label); hash[iter] = temp; que.push(iter); } hash[q]->neighbors.push_back(hash[iter]); //将一个节点的邻接点关系记录下来 } } return hash[node]; }};

题目来源

转载地址:http://lgkmo.baihongyu.com/

你可能感兴趣的文章
IE首页被篡改(手动修复)
查看>>
基于FPGA的图像处理(二)--System Generator入门
查看>>
DIV+CSS 入门
查看>>
UVa 213 Message Decoding(World Finals1991,串)
查看>>
Everything search syntax
查看>>
BZOJ 3211 弗洛拉前往国家 树阵+并检查集合
查看>>
Windows下一个SlikSVN使用
查看>>
DataTable.Compute 性能慢的问题
查看>>
分层是一种思想
查看>>
Windows系统bug
查看>>
Chrome应用技巧之代码整理。
查看>>
Linux下配置Hadoop 1.2.1
查看>>
Fluentd 例子
查看>>
解决上传服务器端文字乱码
查看>>
Makefile生成器,使用C++和Boost实现
查看>>
ITOO之底层关系
查看>>
算法笔记_141:无向图的欧拉回路判断问题(Java)
查看>>
XX年年终总结---重新飞跃
查看>>
js---06函数传参数
查看>>
WCF系列教程之WCF服务配置
查看>>