Clone Graph

典型的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)