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

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

题目如下:实现克隆图的算法  

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         / \         \_/

分析:BFS或者DFS遍历图,遍历的过程中复制节点,用哈希表保存新建立的节点的地址(同时这个哈希表可以用做节点访问标志)代码如下:                                                

1 /** 2  * Definition for undirected graph. 3  * struct UndirectedGraphNode { 4  *     int label; 5  *     vector
neighbors; 6 * UndirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution {10 public:11 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {12 // IMPORTANT: Please reset any member data you declared, as13 // the same Solution instance will be reused for each test case.14 typedef unordered_map
Map;15 if(node == NULL)return NULL;16 Map gmap;//保存克隆图的节点的地址,顺便作为节点是否访问的标记17 stack
gstack;18 UndirectedGraphNode *res = new UndirectedGraphNode(node->label);19 gmap.insert(Map::value_type(res->label, res));20 gstack.push(node);21 while(gstack.empty() == false)22 {23 UndirectedGraphNode *p = gstack.top(), *newp;24 gstack.pop();25 if(gmap.find(p->label) != gmap.end())//查找克隆图节点是否已经构造26 newp = gmap[p->label];27 else28 {29 newp = new UndirectedGraphNode(p->label);30 gmap.insert(Map::value_type(p->label, newp));31 }32 for(int i = 0; i < p->neighbors.size(); i++)33 {34 UndirectedGraphNode *tmp = p->neighbors[i];35 if(gmap.find(tmp->label) == gmap.end())36 {37 gmap.insert(Map::value_type(tmp->label,38 new UndirectedGraphNode(tmp->label)));39 gstack.push(tmp);40 }41 //设置克隆图节点的邻接点42 newp->neighbors.push_back(gmap[tmp->label]);43 }44 }45 return res;46 }47 };

【版权声明】转载请注明出处:

转载于:https://www.cnblogs.com/TenosDoIt/p/3418412.html

你可能感兴趣的文章
小程序安全设置-弹出框输入获取值
查看>>
Electron开发初体验
查看>>
android - 搜索功能
查看>>
JavaScript30 中文指南 - 13 图片随屏幕滚动而滑入滑出的效果指南
查看>>
Git基本操作
查看>>
Spring事务传播行为详解
查看>>
Java图形化:Swing表格的使用
查看>>
MacOS系统Docker默认存储路径迁移方法
查看>>
vscode插件开发实践与demo源码
查看>>
初学UI小知识总结
查看>>
Kotlin--高阶函数
查看>>
多阶段决策问题——DAG(算法竞赛入门经典笔记)
查看>>
UI分析工具YourView开源—App开发者不可多得的利器!
查看>>
记录一次jenkins的部署和使用
查看>>
vscode专题
查看>>
前端基础17:对象/实例/原型
查看>>
tornado 源码之 iostream.py
查看>>
Javascript基础学习干货教程(3)
查看>>
JAVA 泛型理解
查看>>
Git常用命令清单,掌握这些,轻松驾驭版本管理
查看>>