[LeetCode] 133. Clone Graph_ Medium tag: BFS, DFS
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
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 #.
- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [LeetCode] 133. Clone Graph 克隆无向图
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
随机推荐
- Makefile 链接静态库
Linux的静态库是以.a结尾的,要连接静态库有两种方法,一种是在编译命令最后直接加上库路径/库名称. 例如你的库在绝对目录/lib/libtest.a下面你就可以这样来编译$(CC) $(CFLAG ...
- CSS技巧:逐帧动画抖动解决方案
笔者所在的前端团队主要从事移动端的H5页面开发,而团队使用的适配方案是: viewport units + rem.具体可以参见凹凸实验室的文章 – 利用视口单位实现适配布局 . 笔者目前(2017. ...
- Elasticsearch 学习之 分片未分配原因
分片未分配的原因主要有: 1)INDEX_CREATED:由于创建索引的API导致未分配.2)CLUSTER_RECOVERED :由于完全集群恢复导致未分配.3)INDEX_REOPENED :由于 ...
- mysql架构图
整体架构图 访问控制图
- php 函数合并 array_merge 与 + 的区别
array_merge()是PHP语言中的一个函数,作用是将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面.返回作为结果的数组. 如果输入的数组中有相同的字符串键名,该键的键值为最 ...
- [sharepoint]Office Web Apps for SharePoint 2010
Office Web Apps for SharePoint 2010 2012年09月20日 ⁄ 综合 ⁄ 共 908字 ⁄ 字号 小 中 大 ⁄ 评论关闭 After you install Of ...
- Unity3D笔记 GUI 一
要实现的功能: 1.个性化Windows界面 2.减少个性化的背景图片尺寸 3.个性化样式ExitButton和TabButton 4.实现三个选项卡窗口 一.个性化Windows界面 1.1.创建一 ...
- yii---where or该如何使用
今天调试YII项目的时候,遇到一个奇葩的事儿,在调试 where or 查询的时候:调试语句是这样: $str = static::find()->where(['or','username' ...
- vue--子组件主动获取父组件的数据和方法
子组件主动获取父组件的数据和方法 简单示例: this.$parent.数组 this.$parent.方法 示例: <template> <div id="Header& ...
- .NET中的类型对象
.NET中的任何类型,都有对应的一个类型对象.类型对象和类型实例(类型创建的一个对象)不是同一个概念. 类型对象包含类型的静态字段和方法,当类访问静态方法静态字段,实例调用方法时就会去类型对象中查找静 ...