LeetCode: Clone Graph 解题报告

Clone Graph
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 #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
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
/ \
\_/
Solution 1:
使用BFS来解决此问题。用一个Queue来记录遍历的节点,遍历原图,并且把复制过的节点与原节点放在MAP中防止重复访问。
图的遍历有两种方式,BFS和DFS
这里使用BFS来解本题,BFS需要使用queue来保存neighbors
但这里有个问题,在clone一个节点时我们需要clone它的neighbors,而邻居节点有的已经存在,有的未存在,如何进行区分?
这里我们使用Map来进行区分,Map的key值为原来的node,value为新clone的node,当发现一个node未在map中时说明这个node还未被clone,
将它clone后放入queue中处理neighbors。
使用Map的主要意义在于充当BFS中Visited数组,它也可以去环问题,例如A--B有条边,当处理完A的邻居node,然后处理B节点邻居node时发现A已经处理过了
处理就结束,不会出现死循环。
queue中放置的节点都是未处理neighbors的节点。
http://www.cnblogs.com/feiling/p/3351921.html
/*
Iteration Solution:
*/
public UndirectedGraphNode cloneGraph1(UndirectedGraphNode node) {
if (node == null) {
return null;
} UndirectedGraphNode root = null; // store the nodes which are cloned.
HashMap<UndirectedGraphNode, UndirectedGraphNode> map =
new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>(); q.offer(node);
UndirectedGraphNode rootCopy = new UndirectedGraphNode(node.label); // 别忘记这一行啊。orz..
map.put(node, rootCopy); // BFS the graph.
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
UndirectedGraphNode curCopy = map.get(cur); // bfs all the childern node.
for (UndirectedGraphNode child: cur.neighbors) {
// the node has already been copied. Just connect it and don't need to copy.
if (map.containsKey(child)) {
curCopy.neighbors.add(map.get(child));
continue;
} // put all the children into the queue.
q.offer(child); // create a new child and add it to the parent.
UndirectedGraphNode childCopy = new UndirectedGraphNode(child.label);
curCopy.neighbors.add(childCopy); // Link the new node to the old map.
map.put(child, childCopy);
}
} return rootCopy;
}
2014.12.30 Redo:
/*
SOLUTION 3: The improved Version.
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
} HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); // BUG 1: can't use queue , should use LinkedList.
Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>(); q.offer(node); // copy the root node. and then put it into the map.
UndirectedGraphNode nodeCopy = new UndirectedGraphNode(node.label);
map.put(node, nodeCopy); while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll(); // get out the copy node. We guarantee that it has been copied. Because we always put it into the map before
// put it into the queue.
UndirectedGraphNode curCopy = map.get(cur); // go through all the children node.
// Line 71: java.util.ConcurrentModificationException. use cur instead of curCopy
for (UndirectedGraphNode child: cur.neighbors) { if (map.containsKey(child)) {
curCopy.neighbors.add(map.get(child));
} else {
// Only add the child into the map when it is not visited.
q.offer(child); // BUG 3: forget to add the new node into the map.
UndirectedGraphNode childCopy = new UndirectedGraphNode(child.label);
curCopy.neighbors.add(childCopy);
map.put(child, childCopy);
}
}
} return map.get(node);
}
Solution 2:
同样的,我们也可以使用递归DFS来解决此题,思路与上图一致,但为了避免重复运算产生死循环。当进入DFS时,如果发现map中已经有了拷贝过的值,直接退出即可。
题目虽然简单,但主页君仍然考虑了递归的特性使程序简洁。比如:我们拷贝只拷贝根节点,而子节点的拷贝由recursion来完成,这样可以使程序更加简洁。
注意:要先加入到map,再调用rec ,否则会造成不断地反复拷贝而死循环。
/*
Solution 2: Recursion version.
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
} return rec(node, new HashMap<UndirectedGraphNode, UndirectedGraphNode>());
} public UndirectedGraphNode rec(UndirectedGraphNode root, HashMap<UndirectedGraphNode, UndirectedGraphNode> map) {
// If it has been copied, just return the copy node from the map.
UndirectedGraphNode rootCopy = map.get(root);
if (rootCopy != null) {
return rootCopy;
} // if the root is not copied, create a new one.
rootCopy = new UndirectedGraphNode(root.label);
map.put(root, rootCopy); // copy all the child node.
for (UndirectedGraphNode child: root.neighbors) {
// call the recursion to create all the children and add the new children to the copy node.
rootCopy.neighbors.add(rec(child, map));
} return rootCopy;
}
2014.12.30 Redo:
public UndirectedGraphNode cloneGraph1(UndirectedGraphNode node) {
if (node == null) {
return null;
}
return rec(node, new HashMap<UndirectedGraphNode, UndirectedGraphNode>());
}
// SOLUTION 1:
// Try to return a copied cloneGraph.
public UndirectedGraphNode rec(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map) {
// The base case:
if (map.containsKey(node)) {
// If the map has been copied, just return the node.
return map.get(node);
}
// create a new node.
UndirectedGraphNode nodeCopy = new UndirectedGraphNode(node.label);
// BUG 2: should put it into the map first. Because we don't want to copy the same node again in the recursion.
map.put(node, nodeCopy);
for (int i = 0; i < node.neighbors.size(); i++) {
// BUG 1: forget a parameter.
// copy all the children node.
nodeCopy.neighbors.add(rec(node.neighbors.get(i), map));
}
return nodeCopy;
}
Ref: http://m.blog.csdn.net/blog/hellobinfeng/17497883
Code:
LeetCode: Clone Graph 解题报告的更多相关文章
- 【LeetCode】133. Clone Graph 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- 【LeetCode】Permutations 解题报告
全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...
- LeetCode - Course Schedule 解题报告
以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...
- LeetCode: Sort Colors 解题报告
Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...
- 【LeetCode】323. Number of Connected Components in an Undirected Graph 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 并查集 日期 题目地址:https://leetcod ...
- [LeetCode] Clone Graph 无向图的复制
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- [LeetCode] Clone Graph 克隆无向图
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph ...
- [leetcode]Clone Graph @ Python
原题地址:https://oj.leetcode.com/problems/clone-graph/ 题意:实现对一个图的深拷贝. 解题思路:由于遍历一个图有两种方式:bfs和dfs.所以深拷贝一个图 ...
随机推荐
- maven Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4
maven Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4 CreateTime--201 ...
- 〖Linux〗OK6410a蜂鸣器的驱动程序编写全程实录
最近在看一本书,受益匪浅,作者是李宁,下边是编写本次蜂鸣器的全程实录: 1. 了解开发板中的蜂鸣器 1) 查看蜂鸣器buzzer在底板中的管脚信息 2) 查看蜂鸣器在总线中的信息 3) 翻看S3C64 ...
- 解决Mysql中文乱码问题的方案
MySQL会出现中文乱码的原因不外乎下列几点: 1.server本身设定问题,例如还停留在latin12.table的语系设定问题(包含character与collation)3.客户端程式(例如ph ...
- 【laravel5.4】关键字【use】使用
1.在namespace 和 class 之间使用,是引入类文件的意思,命名空间过长或者类文件同名,可以使用[as]区别 2.在class 类里面使用[use],是导入trait 类的意思,多继承的 ...
- 转载【小程序】: 微信小程序开发---应用与页面的生命周期
App App() App() 函数用来注册一个小程序.接受一个 object 参数,其指定小程序的生命周期函数等. object参数说明: 属性 类型 描述 触发时机 onLaunch Functi ...
- php调试利器Xhprof的安装与使用
一.安装xhprof wget http://pecl.php.net/get/xhprof-0.9.4.tgz tar -zxvf xhprof-0.9.4.tgz cd xhprof-0.9.4/ ...
- 内省对象 用的少,被BeanUtils代替
类 描述 BeanInfo 对JavaBean进行描述的接口 Introspector 描述所有的JavaBean的成员类 PropertyDescriptor 描述的是JavaBean的属性类 sh ...
- SPFA 上手题 数 枚:
1, HDU 1548 A strange lift :http://acm.hdu.edu.cn/showproblem.php?pid=1548 这道题可以灰常巧妙的转换为一道最短路题目,对第i层 ...
- RabbitMQ消息队列(六):使用主题进行消息分发[转]
在上篇文章RabbitMQ消息队列(五):Routing 消息路由 中,我们实现了一个简单的日志系统.Consumer可以监听不同severity(严重级别)的log.但是,这也是它之所以叫做简单日志 ...
- POJ 1465 Multiple (BFS,同余定理)
id=1465">http://poj.org/problem?id=1465 Multiple Time Limit: 1000MS Memory Limit: 32768K T ...