1. 程式人生 > >133. Clone Graph

133. Clone Graph

nod ted clas ins rect shm poll node label

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null)
            return null;
        Map<UndirectedGraphNode, UndirectedGraphNode> map=new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        Queue<UndirectedGraphNode> que=new LinkedList<UndirectedGraphNode>();
        que.add(node);
        map.put(node,new UndirectedGraphNode(node.label));
        while(!que.isEmpty())
        {
            UndirectedGraphNode cur=que.poll();
            for(UndirectedGraphNode child:cur.neighbors)
            {
                if(!map.containsKey(child))
                {
                    map.put(child, new UndirectedGraphNode(child.label));
                    que.add(child);
                }
                map.get(cur).neighbors.add(map.get(child));
            }
        }
        return map.get(node);
    }
}

  

133. Clone Graph