133. Clone Graph

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);
    }
}

  

posted @ 2017-10-07 04:47  Weiyu Wang  阅读(122)  评论(0编辑  收藏  举报