首页 > 其他 > 详细

Clone Graph

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

典型的dfs,做个hashmap判断是否存过(oldnode,newnode)

最后怎么把neighbor加入到hm对应node的neighbor list中比较关键

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null) return null;
        HashMap<UndirectedGraphNode,UndirectedGraphNode> hm =  new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        hm.put(node, head);
        dfs(hm, node);
        return head;
    }
    private void dfs(HashMap<UndirectedGraphNode,UndirectedGraphNode> hm , UndirectedGraphNode node){
        if(node ==null) return;
        for(UndirectedGraphNode a_nb: node.neighbors){
            if(!hm.containsKey(a_nb)){
                UndirectedGraphNode nb = new UndirectedGraphNode(a_nb.label);
                hm.put(a_nb,nb);
                dfs(hm, a_nb);
            }
            //这里是关键!!
            hm.get(node).neighbors.add(hm.get(a_nb));
        }
    }
}

 

Clone Graph

原文:http://www.cnblogs.com/jiajiaxingxing/p/4570720.html

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