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. CF 578A A Problem about Polyline

    题意: There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - ( ...

  2. IDX爱定客 | 氪加

    IDX爱定客 | 氪加 个性化定制鞋网站,在线定制只需三分钟

  3. C语言漫谈(二) 图像显示 Windows和Linux

    关于图像显示有很多库可以用,Windows下有GDI,GDI+,D3D等,Linux下有X Window和Wayland,此外还有OpenGL ,SDL等图形库以及各种GUI库. 了解最原始的方式,对 ...

  4. 成语接龙(dfs)

    成语接龙 Time Limit: 1000 MS Memory Limit: 32768 K Total Submit: 92(17 users) Total Accepted: 23(14 user ...

  5. [core Java学习笔记][第一二三章基本语法]

    基本语法 1 Java 简单的类型 1.1 一些常量 正无穷大 Double.POSITVE_INFINITY 负无穷大 Double.NEGATIVE_INFINITY 不存在 Double.NaN ...

  6. Js异步级联选择框实践方法

    HTML: <li> <span>所在地区:</span> <select name="prov" id="ddl_prov&q ...

  7. 《JavaScript 闯关记》之作用域和闭包

    作用域和闭包是 JavaScript 最重要的概念之一,想要进一步学习 JavaScript,就必须理解 JavaScript 作用域和闭包的工作原理. 作用域 任何程序设计语言都有作用域的概念,简单 ...

  8. 黑马程序员 ——Java SE(1)

    ----<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培训 ...

  9. C# 仿百度自动匹配

    private void Form1_Load(object sender, EventArgs e) { AutoCompleteStringCollection source = new Auto ...

  10. Cisco cmd 命令

    1.enable 开启全局配置模式:disable 禁用配置模式 2.config进入配置模式 3.line 设置进入用户模式密码:分为 line aux 0;line console 0;line ...