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. 【云迁移论文笔记】Cloud Migration Research:A Systematic Review

    Cloud Migration Research:A Systematic Review Author Info: Pooyan Jamshidi PhD Postdoctoral Researche ...

  2. ORA-00600: internal error code, arguments: [kgl-no-mutex-held]

    一.环境 windows oracle 11.2.0.4 RAC 二.问题现象 1.连接数据库后,无法查询 2.报错信息:ORA-00600: internal error code, argumen ...

  3. linux ntp时间服务器配置

    Network Time Protocol (NTP) 也是RHCE新增的考试要求. 学习的时候也顺便复习了一下如何设置Linux的时间,现在拿出来和大家分享 设置NTP服务器不难但是NTP本身是一个 ...

  4. 【BZOJ4036】[HAOI2015]按位或 FWT

    [BZOJ4036][HAOI2015]按位或 Description 刚开始你有一个数字0,每一秒钟你会随机选择一个[0,2^n-1]的数字,与你手上的数字进行或(c++,c的|,pascal的or ...

  5. windows10 自带笔记本键盘禁止和开启

    管理员打开cmd,输入sc config i8042prt start= disabled 然后重启就好了,注意 =后面有个空格. 恢复:sc config i8042prt start= deman ...

  6. php---进行签名验证

    为什么要进行签名,我们在进行数据请求的时候,为了防止数据被人截取,造成不好的影响,所以我们在进行数据请求的时候,需要进行签名验证,进行签名的原理是:客户端和服务端使用同样的签名算法,来计算签名,当客户 ...

  7. TFS二次开发08——分支(Branch)和合并(Merge)

    一:创建分支   private static void BranchFile(Workspace workspace, String newFilename) { String branchedFi ...

  8. ELK之写入MySQL数据库

    安装MySQL5.6 创建数据库并且授权 create database elk character set utf8 collate utf8_bin; grant all on elk.* to ...

  9. 1.4激活函数-带隐层的神经网络tf实战

    激活函数 激活函数----日常不能用线性方程所概括的东西 左图是线性方程,右图是非线性方程 当男生增加到一定程度的时候,喜欢女生的数量不可能无限制增加,更加趋于平稳 在线性基础上套了一个激活函数,使得 ...

  10. easyui 特殊操作

    --EasyUI - datagrid中单元格里编辑控件的单击事件如何获取当前行的index var rowIndex = $(this).parents('.datagrid-row').attr( ...