题目:

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. 1
  2. / \
  3. / \
  4. 0 --- 2
  5. / \
  6. \_/

链接: http://leetcode.com/problems/clone-graph/

题解:

拷贝图。图的遍历,主要就是DFS和BFS, 这道题考察基本功。需要注意的地点是如何建立visited数组,这道题因为lable unique,所以可以建立Map<Integer, UndirectedGraphNode>,假如lable有重复值,则建立Map的时候要使用Map<UndirectedGraphNode, UndirectedGraphNode>。 基本题目要多练习,这样拓展到难题以后才能借鉴思路。二刷的时候要注意recursive和iterative。

DFS:

Time Complexity - O(n), Space Complexity - O(n)

  1. /**
  2. * Definition for undirected graph.
  3. * class UndirectedGraphNode {
  4. * int label;
  5. * List<UndirectedGraphNode> neighbors;
  6. * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
  7. * };
  8. */
  9. public class Solution {
  10. HashMap<Integer, UndirectedGraphNode> visited = new HashMap<>();
  11.  
  12. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  13. if(node == null)
  14. return node;
  15. if(visited.containsKey(node.label))
  16. return visited.get(node.label);
  17.  
  18. UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
  19. visited.put(clone.label, clone);
  20.  
  21. for(UndirectedGraphNode neighbor : node.neighbors)
  22. clone.neighbors.add(cloneGraph(neighbor));
  23.  
  24. return clone;
  25. }
  26. }

BFS:

Time Complexity - O(n), Space Complexity - O(n)

  1. /**
  2. * Definition for undirected graph.
  3. * class UndirectedGraphNode {
  4. * int label;
  5. * List<UndirectedGraphNode> neighbors;
  6. * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
  7. * };
  8. */
  9. public class Solution {
  10. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  11. if(node == null)
  12. return node;
  13.  
  14. Queue<UndirectedGraphNode> q = new LinkedList<>();
  15. q.offer(node);
  16. HashMap<Integer, UndirectedGraphNode> visited = new HashMap<>();
  17. visited.put(node.label, new UndirectedGraphNode(node.label));
  18.  
  19. while(!q.isEmpty()) {
  20. UndirectedGraphNode newNode = q.poll();
  21.  
  22. for(UndirectedGraphNode neighbor : newNode.neighbors) {
  23. if(!visited.containsKey(neighbor.label)) {
  24. q.offer(neighbor);
  25. visited.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
  26. }
  27. visited.get(newNode.label).neighbors.add(visited.get(neighbor.label));
  28. }
  29. }
  30.  
  31. return visited.get(node.label);
  32. }
  33. }

二刷:

Java:

DFS:

  1. /**
  2. * Definition for undirected graph.
  3. * class UndirectedGraphNode {
  4. * int label;
  5. * List<UndirectedGraphNode> neighbors;
  6. * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
  7. * };
  8. */
  9. public class Solution {
  10. Map<Integer, UndirectedGraphNode> map = new HashMap<>();
  11.  
  12. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  13. if (node == null) return null;
  14. if (map.containsKey(node.label)) return map.get(node.label);
  15. UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
  16. map.put(newNode.label, newNode);
  17.  
  18. for (UndirectedGraphNode neighbor : node.neighbors) {
  19. newNode.neighbors.add(cloneGraph(neighbor));
  20. }
  21. return newNode;
  22. }
  23. }

BFS:

  1. /**
  2. * Definition for undirected graph.
  3. * class UndirectedGraphNode {
  4. * int label;
  5. * List<UndirectedGraphNode> neighbors;
  6. * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
  7. * };
  8. */
  9. public class Solution {
  10. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  11. if (node == null) return null;
  12. Queue<UndirectedGraphNode> q = new LinkedList<>();
  13. q.offer(node);
  14. Map<Integer, UndirectedGraphNode> visited = new HashMap<>();
  15. visited.put(node.label, new UndirectedGraphNode(node.label));
  16.  
  17. while (!q.isEmpty()) {
  18. UndirectedGraphNode oldNode = q.poll();
  19. for (UndirectedGraphNode neighbor : oldNode.neighbors) {
  20. if (!visited.containsKey(neighbor.label)) {
  21. q.offer(neighbor);
  22. visited.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
  23. }
  24. visited.get(oldNode.label).neighbors.add(visited.get(neighbor.label));
  25. }
  26. }
  27. return visited.get(node.label);
  28. }
  29. }

Reference:

http://www.cnblogs.com/springfor/p/3874591.html

http://blog.csdn.net/linhuanmars/article/details/22715747

http://blog.csdn.net/fightforyourdream/article/details/17497883

http://www.programcreek.com/2012/12/leetcode-clone-graph-java/

https://leetcode.com/discuss/26988/depth-first-simple-java-solution

https://leetcode.com/discuss/44330/java-bfs-solution

https://leetcode.com/discuss/14969/simple-java-iterative-bfs-solution-with-hashmap-and-queue

133. Clone Graph的更多相关文章

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

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

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

  4. leetcode 133. Clone Graph ----- java

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

  5. 133. Clone Graph(图的复制)

    Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains ...

  6. 133. Clone Graph (Graph, Map; DFS)

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

  7. Graph 133. Clone Graph in three ways(bfs, dfs, bfs(recursive))

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

  8. Java for LeetCode 133 Clone Graph

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

  9. [LeetCode] 133. Clone Graph 克隆无向图

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

随机推荐

  1. C#当中的泛型和java中的对比

    1.C#中的泛型 先写一个Demo: namespace generic {         public class Program         {                 static ...

  2. 反汇编windows htonl()函数

    因为自己在系统内核写网络程序有时候需要调用htons htonl 这样的函数进行转换,但由于内核只能调用c运行库,别的API不能调用.自己也接触过一点汇编,从来没有去学过.看过老码识途这本书前几章,如 ...

  3. Centos7最小化安装后(minimal)安装图形界面

    centos7下载地址:http://mirrors.cqu.edu.cn/CentOS/7/isos/x86_64/CentOS-7-x86_64-Minimal-1511.iso 下载后用vmwa ...

  4. CSS3滤镜!!!

    <!DOCTYPE html> <html> <head> <style> img { width: 33%; height: auto; float: ...

  5. checkbox prop()函数

    1.设置checkbox选中状态 ①选中: .prop('checked',true); ②不选中:.prop('checked',false); 2.获取checkbox选中状态 .prop('ch ...

  6. 九度OJ 1349 数字在排序数组中出现的次数 -- 二分查找

    题目地址:http://ac.jobdu.com/problem.php?pid=1349 题目描述: 统计一个数字在排序数组中出现的次数. 输入: 每个测试案例包括两行: 第一行有1个整数n,表示数 ...

  7. Aspose.word总结

    1.创建word模版,使用MergeFeild绑定数据     新建一个Word文档,命名为Template.doc     注意:这里并不是输入"<”和“>”就可以了,而是必须 ...

  8. DOM五大对象

    1.Window 对象:Window 对象表示浏览器中打开的窗口. 如果文档包含框架(frame 或 iframe 标签),浏览器会为 HTML 文档创建一个 window 对象,并为每个框架创建一个 ...

  9. 用twisted 做一个日志收集系统

    混沌初开 起初我是不会上logging模块的,直接导致了即时有了日志,我也存到了数据库中,而且量也不大,是否能遇到异常只能靠运气了 开天辟地 不得不说,没有任何输出的线上环境真的挺难调试的,当然,聪明 ...

  10. jquery 验证插件 validate

    1)required:true 必输字段(2)remote:"check.php" 使用ajax方法调用check.php验证输入值(3)email:true 必须输入正确格式的电 ...