IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode Clone Graph

    yangliuy发表于 2015-03-29 12:36:21
    love 0

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

    思路分析:这题考察图的遍历,可以考虑DFS或者BFS对图进行搜索遍历,同时进行图拷贝。下面给出了BFS基于队列的迭代实现解法。比较巧妙的是,需要用到一个HashMap来保存原来的graph的节点和新生成的graph的节点的对应关系,当在原图中BFS遍历当前节点的相邻节点时,要同时在新图对应节点的相邻节点集合中进行相应节点的添加操作。同时这个HashMap的key域还可以当成visited访问标记集合来使用,只添加没有访问过的相邻节点到队列中。每个节点访问一次,时间复杂度和空间复杂度都是O(n).

    AC Code

    /**
     * Definition for undirected graph.
     * class UndirectedGraphNode {
     *     int label;
     *     List neighbors;
     *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
     * };
     */
    public class Solution {
        public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            //0923
            if(node == null) return null;
            HashMap map = new HashMap(); //key old graph node; value new graph node
            UndirectedGraphNode newGraphNode = new UndirectedGraphNode(node.label);
            newGraphNode.neighbors = new ArrayList();
            if(node.neighbors.isEmpty()) return newGraphNode;
            LinkedList queue = new LinkedList();
            queue.add(node);
            map.put(node, newGraphNode);
            while(!queue.isEmpty()){
                UndirectedGraphNode curNode = queue.poll();
                for(UndirectedGraphNode nnode : curNode.neighbors){
                    if(!map.containsKey(nnode)){
                        UndirectedGraphNode copyNode = new UndirectedGraphNode(nnode.label);
                        map.put(nnode, copyNode);
                        queue.add(nnode);
                    }
                    map.get(curNode).neighbors.add(map.get(nnode));
                }
            }
            return newGraphNode;
        }
    }




沪ICP备19023445号-2号
友情链接