Question

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
/ \
\_/

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 解答的更多相关文章

  1. 21. Clone Graph

    Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...

  2. 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 ...

  3. [LeetCode]Copy List with Random Pointer &amp;Clone Graph 复杂链表的复制&amp;图的复制

    /** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label ...

  4. 【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 ...

  5. LeetCode: Clone Graph 解题报告

    Clone GraphClone an undirected graph. Each node in the graph contains a label and a list of its neig ...

  6. [Leetcode Week3]Clone Graph

    Clone Graph题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/clone-graph/description/ Description Clon ...

  7. 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 ...

  8. Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph)

    Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tree ...

  9. [LeetCode] Clone Graph 无向图的复制

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

随机推荐

  1. vijos1777 引水入城

    描述 在一个遥远的国度,一侧是风景秀美的湖泊,另一侧则是漫无边际的沙漠.该国的行政区划十分特殊,刚好构成一个N行M列的矩形,其中每个格子都代表一座城市,每座城市都有一个海拔高度. 为了使居民们都尽可能 ...

  2. libeXosip2(1) -- Modules

    Modules Here is a list of all modules: [detail level 12] The eXtented eXosip stack LibeXosip2 Versio ...

  3. 第12讲- Android之消息提示Toast

    第12讲 Android之消息提示Toast .Toast Toast 是一个 View 视图,在应用程序上浮动显示少量的信息给用户,它永远不会获得焦点,不影响用户的输入等操作,主要用于向用户显示一些 ...

  4. 第05讲- DDMS中logcat的使用

    第05讲 DDMS中logcat的使用 1.DDMS DDMS 的全称是Dalvik Debug Monitor Service,是 Android 开发环境中的Dalvik虚拟机调试监控服务.DDM ...

  5. JAVA读、写EXCEL文件

    採用jxl.jar包,网上下载,百度一下到出都是.希望能够帮助到大家. 接下来直接贴代码: <span style="font-size:18px;"> public ...

  6. Java中出现“错误: 编码GBK的不可映射字符”的解决方法

    我的java文件里出现中文,是这样一个文件: import java.io.*; public class Test { public static void main(String[] args) ...

  7. 触摸点为scrollview上的子控件时,scrollview不能滚动(iOS8)

    现象:在iOS8上,scrollview上面布局了多行多列的button,滑动scrollview,如果当触摸点是在按钮上,scrollview不能滚动. 例如: 解决方法:设置scrollview的 ...

  8. JQuery 之事件中的 ----- hover 与 onmouseover 、onmouseout 联系

    hover([over,]out) 一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法.这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态. 当鼠标移动到一个匹配的元素 ...

  9. 纯css实现下拉菜单

    今天给大家分享一个纯html+css实现的下拉菜单.在此声明一点,源码并非出自本人之手,是同项目组一兄弟PLUTO写的.好东西嘛,所以果断拿出来和大家分享.如果有更好的想法或者建议,一定记得留言哦!好 ...

  10. eclipse中多个工程编译到同一个目录下

    1.点击link source  2.选择Java(ps:Java文件目录)或者resource(ps:配置文件目录)  3.最后结果,然后使用project中的clean进行编译,就可以把两个工程编 ...