码迷,mamicode.com
首页 > 其他好文 > 详细

Clone Graph

时间:2015-06-12 06:29:21      阅读:119      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!