• 133. Clone Graph


    题目:

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

    链接: 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)

    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        HashMap<Integer, UndirectedGraphNode> visited = new HashMap<>();
        
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if(node == null)
                return node;
            if(visited.containsKey(node.label))
                return visited.get(node.label);
            
            UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
            visited.put(clone.label, clone);
            
            for(UndirectedGraphNode neighbor : node.neighbors)
                clone.neighbors.add(cloneGraph(neighbor));
            
            return clone;
        }
    }

    BFS:

    Time Complexity - O(n), Space Complexity - 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 node;
            
            Queue<UndirectedGraphNode> q = new LinkedList<>();
            q.offer(node);
            HashMap<Integer, UndirectedGraphNode> visited = new HashMap<>();
            visited.put(node.label, new UndirectedGraphNode(node.label));
            
            
            while(!q.isEmpty()) {
                UndirectedGraphNode newNode = q.poll();
                
                for(UndirectedGraphNode neighbor : newNode.neighbors) {
                    if(!visited.containsKey(neighbor.label)) {
                        q.offer(neighbor);
                        visited.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
                    }
                    visited.get(newNode.label).neighbors.add(visited.get(neighbor.label));
                }
            }
            
            return visited.get(node.label);
        }
    }

    二刷:

    Java:

    DFS:

    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List<UndirectedGraphNode> neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     * };
     */
    public class Solution {
        Map<Integer, UndirectedGraphNode> map = new HashMap<>();
        
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            if (node == null) return null;
            if (map.containsKey(node.label)) return map.get(node.label);
            UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
            map.put(newNode.label, newNode);
            
            for (UndirectedGraphNode neighbor : node.neighbors) {
                newNode.neighbors.add(cloneGraph(neighbor));
            }
            return newNode;
        }
    }

    BFS:

    /**
     * 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;
            Queue<UndirectedGraphNode> q = new LinkedList<>();
            q.offer(node);
            Map<Integer, UndirectedGraphNode> visited = new HashMap<>();
            visited.put(node.label, new UndirectedGraphNode(node.label));
            
            while (!q.isEmpty()) {
                UndirectedGraphNode oldNode = q.poll();
                for (UndirectedGraphNode neighbor : oldNode.neighbors) {
                    if (!visited.containsKey(neighbor.label)) {
                        q.offer(neighbor);
                        visited.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
                    }
                    visited.get(oldNode.label).neighbors.add(visited.get(neighbor.label));
                }
            }
            return visited.get(node.label);
        }
    }

    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

  • 相关阅读:
    MongoDB学习笔记~Mongo集群和副本集
    知方可补不足~写了一个计算数据表占用存储空间的方法
    MongoDB学习笔记~为IMongoRepository接口添加分页取集合的方法
    MongoDB学习笔记~索引提高查询效率
    MongoDB学习笔记~客户端命令行的使用
    Android动画效果translate、scale、alpha、rotate详解
    CacheHelper工具类的使用
    [置顶] vs2008 编译adb 支持4.2 android 系统(增加push 命令的进度)
    如何在cocos2d项目中enable ARC
    敏捷开发用户故事系列之十一:CSDN博客用户故事分析
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438775.html
Copyright © 2020-2023  润新知