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盒子模型

    [摘要]盒子模型是CSS中的一个重要概念,虽然CSS中没有盒子这个单独的属性对象,但它却是CSS中无处不在的一个重要组成部分.掌握盒子模型的原理和使用方法可以极大地丰富HTML元素的表现效果,同时对于 ...

  2. springbatch---->springbatch的使用(四)

    这里我们重点学习一下springbatch里面的各种监听器的使用,以及job参数的传递.追求得到之日即其终止之时,寻觅的过程亦即失去的过程. springbatch的监听器 一.JOB LISTENE ...

  3. 用CornerStone配置SVN,HTTP及svn简单使用说明

    转载 http://my.oschina.net/joanfen/blog/194491 一.下载地址 CornerStoneV2.6:http://pan.baidu.com/s/1qWEsEbM密 ...

  4. CF 434C Tachibana Kanade's Tofu[数位dp+AC自动机]

    Solution //本代码压掉后两维 #include<cstdio> #define max(a,b) (a<b?b:a) using namespace std; inline ...

  5. 【转】失效迭代器(Invalidating Iterators)

      当一个容器变化时,指向该容器中元素的迭代器可能失效.这使得在迭代器变化期间改变容器容易出现问题.在这方面,不同的容器提供不同的保障:vectors: 引起内存重新分配的插入运算使所有迭代器失效,插 ...

  6. C程序设计语言习题(3-5)

    编写函数itob(n,s,b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中.e.g.itob(n,s,16)把整数n格式化为十六进制整数保存在s中. #include< ...

  7. HTML5 Canvas 画纸飞机组件

    纸飞机模拟一个物体在规定设计轴线偏离方位. //三角形 function DrawTriangle(canvas, A, B, C) { //画个三角形,“A.B.C”是顶点 with (canvas ...

  8. layer.load()加载层如何加入文字描述

    https://fly.layui.com/jie/3586/ https://www.layui.com/doc/modules/layer.html#layer.load //loading层va ...

  9. wpgcms---设置应用模板

    wpgcms设置应用模板,找了好半天才找到. 第一步:找到对应的应用(例如:案例) 选择“界面”,前台页面 设置列表模板: 设置详情模板:

  10. APM飞控的使用心得

    硬件资源:APM,F450四轴机架,大疆电调和电机,富斯i6控和接收机. 刚开始的步骤都是大同小异,首先可以按照这个链接上面的步骤一步步的执行:http://tieba.baidu.com/p/297 ...