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. css - 文字元素等的美化效果代码汇总(更新中...)

    投影的设置 -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparen ...

  2. IPhoneX网页布局 全屏布局(转)

    IPhoneX全面屏是十分科技化的,但是由于其圆角和摄像头刘海位置以及操控黑条的存在使得我们需要去对其样式做一些适配,没有X的同学可以开启 Xcode 9 的iPhone X 模拟器作为学习和调试. ...

  3. Android 查看system/bin目录下支持哪些命令?

    C:\Users\yonghuming>adb shell "ls system/bin" >log acpiadbdamapp_processapp_process3 ...

  4. Struts2之Action三种接收参数形式与简单的表单验证

    有了前几篇的基础,相信大家对于Struts2已经有了一个很不错的认识,本篇我将为大家介绍一些关于Action接收参数的三种形式,以及简单的表单验证实现,下面进入正题,首先我们一起先来了解一下最基本的A ...

  5. 去掉VS2010代码中文注释的红色下划线

    VS2010代码中文注释出现红色下划线,代码看上去很不美观,发现是由于安装Visual Assist X插件造成的. 解决办法:打开VAX的Options对话框,取消Advanced --> U ...

  6. Nexus网页直接上传jar包

    登陆已经安装好的nexus私有仓库,如图:   点击左边菜单“Repositories”,选择右边列表“3rd party“   点击“3rd party”,选择artifact Upload,如下图 ...

  7. AD添加LOGO的方法

    1 将logo图片转换成单色的BMP 图像.简单的方法是使用Windows自带的画图程序,在将图片另存为时, 在文件类型下拉列表中选择单色.bmp即可.我们以Altium为例,如图所示将蓝色logo另 ...

  8. nagios监控报错 It appears as though you do not have permission to view...

    今天在安装完nagios后,通过nagios网页界面点击主机.服务.问题页面时.均报错,报错的内容都差不多.如点击服务,报错: It appears as though you do not have ...

  9. linux系统下邮件的发送

    在linux系统下发送邮件一般都要要求本地的机器必须安装和启动Sendmail服务,配置非常麻烦,而且会带来不必要的资源占用. 其实我还可以安装mailx软件,通过修改配置文件可以使用外部SMTP服务 ...

  10. java成员变量和局部变量的初始化和内存中的运行机制

    成员变量: 当系统加载类或创建类的实例时,系统会自动为成员变量分配内存空间,并在分配内存空间后,自动为成员变量指定初始值. eyeNum是类属性.name是实例属性 所有person实例访问eyeNu ...