133. Clone Graph【M】【73】【图的遍历】【再来一遍】【vip】
2016-05-27 12:33
148 查看
Clone an undirected graph. Each node in the graph contains a
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
a separator for node label and each neighbor of the node.
As an example, consider the serialized graph
The graph has a total of three nodes, and therefore contains three parts as separated by
First node is labeled as
both nodes
Second node is labeled as
node
Third node is labeled as
node
Visually, the graph looks like the following:
Subscribe to see which companies asked this question
https://leetcode.com/discuss/57285/python-solutions-bfs-dfs-iteratively-dfs-recursively
labeland 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
0to
both nodes
1and
2.
Second node is labeled as
1. Connect node
1to
node
2.
Third node is labeled as
2. Connect node
2to
node
2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
Subscribe to see which companies asked this question
https://leetcode.com/discuss/57285/python-solutions-bfs-dfs-iteratively-dfs-recursively
# Definition for a undirected graph node # class UndirectedGraphNode(object): # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution(object): def cloneGraph(self, node): if not node: return res = {} root = UndirectedGraphNode(node.label) res[node] = root n = node q = while q: cur = q[0] q = q[1:] for i in cur.neighbors: if i not in res: q += i, nb = UndirectedGraphNode(i.label) res[i] = nb res[cur].neighbors += nb, else: #原来写成了,这样一来,就是把没有复制的直接给放到新的里面去了。。 #res[cur].neighbors += i, res[cur].neighbors += res[i], return root#res[node.label]
相关文章推荐
- 摘要:我们经常会用到递归函数,但是如果递归深度太大时,往往导致栈溢出。而递归深度往往不太容易把握,所以比较安全一点的做法就是:用循环代替递归。文章最后的原文里面讲了如何用10步实现这个过程,相当精彩。本文翻译了这篇文章,并加了自己的一点注释和理解。
- “两学一做”知识竞赛试题(附答案)
- 荷兰国旗问题
- 92-Integer Break
- poj之旅——3614
- Sublime Text自定制代码片段(Code Snippets)
- 阅读王垠《怎样写一个解释器》一文后的一些体会
- Scrollview 嵌套 RecyclerView 及在Android 5.1版本滑动时 惯性消失问题
- Linux下Kill函数用法
- sprint个人总结+读书博客
- Android 属性动画(Property Animation) 完全解析 (上)
- 微信硬件平台的基础接入和硬件云标准接入分析
- 使用NOPI实现Excel导入导出类
- ThinkPHP3.2.3学习笔记5---模板(一)
- iOS项目中引用多个第三方库引发冲突的解决方法
- css3元素简单的闪烁效果
- C++第14周项目模板【项目1-排序函数模板】
- C Tricks(七)—— 有序向量的去重
- maven jar包上传中央仓库 操作
- 试用阿里云RDS的MySQL压缩存储引擎TokuDB