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. C++ #include—尖括号和双引号的区别

    如果你还看一些别的C++教程,那么你可能很早就发现了,有些书上的#include命令写作#include <文件名>,但有时候又会出现#include "文件名".你会 ...

  2. 字符串处理总结之一(C#String类)

    C#(静态String类) C#中提供了比较全面的字符串处理方法,很多函数都进行了封装为我们的编程工作提供了很大的便利.System.String是最常用的字符串操作类,可以帮助开发者完成绝大部分的字 ...

  3. SharpGL学习笔记(四) 正射投影

    上节谈到投影变换分为透视投影(perspective projection)和正射投影(orthographic projection)两种. 透视投影我们已经介绍过了, 现在谈谈正视投影. 正射投影 ...

  4. 在winform上内嵌入其它的程序

    这段代码很有意义,用于把一个程序的界面嵌入到我们自己程序的某个指定窗体上. 比如在某个项目里,我需要把基恩士的激光扫描轮廓显示给客户看,但是激光的DLL中并没有这种功能提供. 于是我想先启动激光的官方 ...

  5. kafka进阶

    1. kafka整体结构图 Kafka名词解释和工作方式 Producer :消息生产者,就是向kafka broker发消息的客户端. Consumer :消息消费者,向kafka broker取消 ...

  6. C语言程序设计--指针基础

    指针 指针是一种特殊变量(存储内存地址).当然它本身也是占用内存的,所以会带来一个问题,那就是指针存在以下概念:指针的类型(int* 一个整型指针),指针指向的类型(int* p = 5, 说明指针p ...

  7. tornado web开发

      tornado是python的web框架,这里简单记录下利用tornado怎么实现文件的上传,其中web.py上传功能类似. 直接用代码说明: 代码来自:http://my.oschina.net ...

  8. 【CF883B】Berland Army 拓扑排序

    [CF883B]Berland Army 题意:给出n个点,m条有向边,有的点的点权已知,其余的未知,点权都在1-k中.先希望你确定出所有点的点权,满足: 对于所有边a->b,a的点权>b ...

  9. Windows Server 2008 R2之六活动目录域服务的卸载

    活动目录域服务的卸载是将DC降级为独立服务器或成员服务器的过程. 在删除活动目录之前,为了防止操作失败操作系统故障,须对系统进行备份.同时,我们还必须对待删除的域控制器进行如下检查 1.是否有操作主控 ...

  10. block 的细节和本质

    案例1: 普通的局部变量,block内部只会引用它初始的值(block定义那一刻),不能跟踪它的改变 输出:1 案例2: block内部能够一直引用被__block修饰的变量 输出:2 案例3: bl ...