首页 > 其他 > 详细

第十篇 Clone Graph

时间:2015-12-22 06:27:31      阅读:182      评论:0      收藏:0      [点我收藏+]

DFS, hashmap记录已经复制过的node

/**
 * 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) {
        HashMap<Integer, UndirectedGraphNode> copied = new HashMap<Integer, UndirectedGraphNode>();
        UndirectedGraphNode root = cloneGraphHelper(node, copied);
        return root;
    }
    private UndirectedGraphNode cloneGraphHelper(UndirectedGraphNode node, HashMap<Integer, UndirectedGraphNode> copied)  {
        if (node == null) {
            return null;
        }
        if (copied.get(node.label) != null) {
            return copied.get(node.label);
        }
        UndirectedGraphNode root = new UndirectedGraphNode(node.label);
        copied.put(root.label, root);
        for (UndirectedGraphNode n : node.neighbors) {
            root.neighbors.add(cloneGraphHelper(n, copied));
        }
        return root;
    }
}

 

第十篇 Clone Graph

原文:http://www.cnblogs.com/ilovenaomi/p/5065452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!