Clone Graph 解答
Question
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
/ \
\_/
Review
This is a classic question which can be solved by DFS and BFS.
Review for DFS and BFS on Graph.
Solution 1 -- BFS
We can use BFS to traverse original graph, and create new graph.
1. Classic way to implement BFS is by queue. There is another class in Java, LinkedList, which has both list and deque's interface. It can also act as queue.
2. We also need to record whether a node in original graph has been visited. When a node in original graph was visited, it means that a node in new graph was created. Therefore, we create a map to record.
Time complexity O(n), space cost O(n)
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null)
return null;
UndirectedGraphNode newHead = new UndirectedGraphNode(node.label);
// Create a queue for BFS
LinkedList<UndirectedGraphNode> ll = new LinkedList<UndirectedGraphNode>();
ll.add(node);
// Create a map to record visited nodes
Map<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
hm.put(node, newHead);
while (ll.size() > 0) {
UndirectedGraphNode tmpNode = ll.remove();
UndirectedGraphNode currentNode = hm.get(tmpNode);
List<UndirectedGraphNode> neighbors = tmpNode.neighbors;
for (UndirectedGraphNode neighbor : neighbors) {
if (!hm.containsKey(neighbor)) {
// If the neighbor node is not visited, add it to the list, hashmap and current node's neighbor
UndirectedGraphNode copy = new UndirectedGraphNode(neighbor.label);
currentNode.neighbors.add(copy);
ll.add(neighbor);
hm.put(neighbor, copy);
} else {
// If the neighbor node is already visited, just add it to current node's neighbor
UndirectedGraphNode copy = hm.get(neighbor);
currentNode.neighbors.add(copy);
}
}
}
return newHead;
}
}
Solution 2 -- DFS
Usually, we use recursion to implement DFS. We also need a map to record whether a node has been visited. Time complexity O(n), space cost O(n).
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null)
return null;
UndirectedGraphNode newHead = new UndirectedGraphNode(node.label);
Map<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
hm.put(node, newHead);
DFS(hm, node);
return newHead;
} private void DFS(Map<UndirectedGraphNode, UndirectedGraphNode> hm, UndirectedGraphNode node) {
UndirectedGraphNode currentNode = hm.get(node);
List<UndirectedGraphNode> neighbors = node.neighbors;
for (UndirectedGraphNode neighbor : neighbors) {
if (!hm.containsKey(neighbor)) {
UndirectedGraphNode copy = new UndirectedGraphNode(neighbor.label);
currentNode.neighbors.add(copy);
hm.put(neighbor, copy);
DFS(hm, neighbor);
} else {
UndirectedGraphNode copy = hm.get(neighbor);
currentNode.neighbors.add(copy);
}
}
}
}
Clone Graph 解答的更多相关文章
- 21. Clone Graph
Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...
- 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表
133. Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of it ...
- [LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label ...
- 【LeetCode】133. Clone Graph (3 solutions)
Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...
- LeetCode: Clone Graph 解题报告
Clone GraphClone an undirected graph. Each node in the graph contains a label and a list of its neig ...
- [Leetcode Week3]Clone Graph
Clone Graph题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/clone-graph/description/ Description Clon ...
- 133. Clone Graph (3 solutions)——无向无环图复制
Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...
- Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph)
Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tree ...
- [LeetCode] Clone Graph 无向图的复制
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
随机推荐
- 《Algorithms 4th Edition》读书笔记——3.1 符号表(Elementary Symbol Tables)-Ⅲ
3.1.3 用例举例 在学习它的实现之前我们还是应该先看看如何使用它.相应的我们这里考察两个用例:一个用来跟踪算法在小规模输入下的行为测试用例和一个来寻找更高效的实现的性能测试用例. 3.1.3.1 ...
- PHP批量审核后台
/*批量审核方法*/ function setOn_all() { if($_POST) { $p=M('news'); $data=array(); $i=0; foreach ($_POST as ...
- yii2学习的论坛
http://www.yiifans.com/forum.php http://www.yiichina.com/ http://www.yiichina.com/
- vim 的配色方案
浅色: http://www.vimninjas.com/2012/09/14/10-light-colors/ 深色: http://www.vimninjas.com/2012/08/26/10- ...
- Hopscotch(细节)
Hopscotch Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u Submit ...
- Working with Numbers in PL/SQL(在PL/SQL中使用数字)
This article gives you all the information you need in order to begin working with numbers in your P ...
- java集合总结【转】
Map.Set.Iterator迭代详解 Map接口定义了四种类型的方法,每个Map都包含这些方法. equals(Object o)比较指定对象与此Map的等价性. hashCode()返回此Map ...
- 关于使用STL常见的两个bug
1.bug 1 class CTest { public : vector<int> getVector() const //需要写成引用形式,不然下面begin.end调用会以拷贝形式调 ...
- vue-resource插件使用
本文的主要内容如下: 介绍vue-resource的特点 介绍vue-resource的基本使用方法 基于this.$http的增删查改示例 基于this.$resource的增删查改示例 基于int ...
- 关于js中select的简单操作,以及js前台计算,span简单操作
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...