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 a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []

这个题的思路是用BFS 或者 DFS, 然后这个题目我们加一个dictionary去节省反复进入某个loop里面.

1. Constraints

1) node id is unique for all nodes

2) 可能为empty

2. Ideas

T: O(n)   S: O(n)

1) d = {}去save original node and new node created, if created, then dont need to keep looping.

2) otherwise, create root and recursively calling root.neighbors

T: O(n) . S: O(n)

1) 还是用visited = {} 去保存original node 和new node, 不过先不管neighbours,先copy所有的node

2) copy 所有node 的neighbors

3. code

 UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors class Solution:
def cloneGraph(self, node):
def dfs(node):
if not node: return
if node in d: return d[node]
root = UndirectedGraphNode(node.label)
d[node] = root
for each in node.neighbors:
if each in d:
root.neighbors.append(d[each])
else:
root.neighbors.append(dfs(each))
return root
d = {}
return dfs(node)

2. Code

# Using BFS
class Node:
def __init__(self, x, neighbors):
self.val = x
self.neighbors = neighbors import collections
class Solution:
def cloneGraph(self, node):
if not node: return
visited, root, queue = {}, node, collections.deque([node])
while queue: # copy nodes
popNode = queue.popleft()
if popNode not in visited:
visited[popNode] = Node(popNode.val, [])
for each in popNode.neighbors:
queue.append(each)
# copy neighbors
for oriNode, copyNode in visited.items():
for each in oriNode.neighbors:
copyNode.neighbors.append(visited[each])
return visited[root]

[LeetCode] 133. Clone Graph_ Medium tag: BFS, DFS的更多相关文章

  1. [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  2. [LeetCode] 103. Binary Tree Zigzag Level Order Traversal _ Medium tag: BFS

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...

  3. [LeetCode] 490. The Maze_Medium tag: BFS/DFS

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  4. [LeetCode] 207 Course Schedule_Medium tag: BFS, DFS

    There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prereq ...

  5. [LeetCode] 261. Graph Valid Tree _ Medium tag: BFS

    Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), w ...

  6. [LeetCode] 200. Number of Islands_ Medium tag: BFS

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...

  7. [LeetCode] 199. Binary Tree Right Side View_ Medium tag: BFS, Amazon

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  8. [Leetcode] 863. All Nodes Distance K in Binary Tree_ Medium tag: BFS, Amazon

    We are given a binary tree (with root node root), a target node, and an integer value `K`. Return a ...

  9. [LeetCode] 133. Clone Graph 克隆无向图

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

随机推荐

  1. Node.js- sublime搭建node的编译环境

    自动配置: 1.安装package control(见 http://www.cnblogs.com/padding1015/p/7763014.html) 2.sublime编辑器中,按快捷键:ct ...

  2. Android 性能分析工具 TraceView

    官方地址 http://developer.android.com/tools/debugging/debugging-tracing.html 推荐:http://blog.csdn.net/inn ...

  3. 如何在mysql中查询每个分组的前几名

    问题 在工作中常会遇到将数据分组排序的问题,如在考试成绩中,找出每个班级的前五名等.  在orcale等数据库中可以使用partition 语句来解决,但在MySQL中就比较麻烦了.这次翻译的文章就是 ...

  4. Web Uploader在低版本IE下无法显示Flash的一种情况

    用户反馈在IE 8下无法正常显示Web Uploader控件,并已安装了Flash插件.调试发现在内部抛出了Runtime Error的错误,关键代码如下: Runtime.create = func ...

  5. Artech的MVC4框架学习——第四章Model元数据的解析

    总结: 第一Model元数据是针对 数据类型的一种表述信息. 第二Model元数据作用:控制数据类型本身及其成员,通过相应的特性,在view中 为绑定的数据(Model)实现模版化的html呈现. 第 ...

  6. exml自动加载图片

    常规H5和微信小游戏同样有效 一.exml自动加载图片 有两张图片 图片未放入defatult.res.json的资源组里,未预先加载包含2张图片的资源组,仅仅在default.res.json里有图 ...

  7. STM32 ADC转换时间

    STM32F103XX的ADC的采样时钟最快14MHz,最快采样率为1MHz. ADC时钟: 这个ADC时钟是从哪来的呢.我们看下面这个STM32的时钟结构图: 我们大多使用STM32的最快PCLK2 ...

  8. listctrl查找定位 使用测试过还很好用

    35.listctrl查找定位  使用测试过还很好用 // 简单的查找函数// FindString(CListCtrl& , 查找内容 , 开始位置 , 到达底部时是否从头查找) int F ...

  9. 关于webpy模板自动HTML转义的问题

    注意: web.py 将会转义任何任何用到的变量,所以当你将 name 的值设为是一段 HTML 时,它会被转义显示成纯文本.如果要关闭该选项,可以写成 $:name 来代替 $name. 如果我们想 ...

  10. c++之list的用法

    list同vector一样是c++中的一个模板类.关于它的详细内容可查看c++的文档 http://www.cplusplus.com/reference/list/list/ C++中list的使用 ...