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. Spring HTTP invoker 入门

    一.简介 Spring开发团队意识到RMI服务和基于HTTP的服务(如,Hessian)之间的空白.一方面,RMI使用JAVA标准的对象序列化机制,很难穿透防火墙.另一方面,Hessian/Burla ...

  2. JS中简单的this学习

        我在学习JS初期,在使用this的时候经常出现问题,当然就是在现在,也有一些场景不能很好的明白this到底指代的是什么?看下面一个例子:   var x = 10; var foo = { x ...

  3. Hibernate框架增删改查测试类归为一个类

    package cn.happy.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org ...

  4. java获取指定长度随机数(版本1)

    获取指定长度随机数,含大小写字母和数字 package org.sw; import java.util.Random; /** * 得到指定位数的随机数 * @author mengzw * @si ...

  5. Android 定义重名权限问题

    一直以来对android的权限机制就有一个疑问,因为在使用权限时,实际上只需要permission的name这一个标签,而在定义权限时,android是不会检查是否重名的,那么在两个应用定义了重名权限 ...

  6. java合并list

    import java.util.ArrayList; import java.util.List;   import com.google.common.collect.Lists;   priva ...

  7. iOS 开发者证书总结

    iOS 证书分两种类型. 第一种为$99美元的,这种账号有个人和公司的区别,公司账号能创建多个子账号,但个人的不能.这种账号可以用来上传app store 第二种为¥299美元的,这种账号只能用于企业 ...

  8. iOS 之改变状态栏颜色

    1.在工程中找到 info.plist  文件,点击“+”号,选择 View controller-based status bar appearance 并设为 NO 2.在 AppDelegate ...

  9. 【转】研华Adam6060某段时间后无法连接的问题

    配合乙方测试,需连接现场Adam模块.一段时间后发现模块无法连接,网上资料甚少,发现此贴,记录下.以前没有多客户端高频次(其实谈不上高)连接,没有考虑连接释放的问题.另外,官方Demo也没有释放连接. ...

  10. OpenCV——IplImage

    IplImage结构: typedef struct _IplImage { int nSize; /* IplImage大小 */ int ID; /* 版本 (=0)*/ int nChannel ...