133. Clone Graph

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null)
            return null;
        
        Map<UndirectedGraphNode, UndirectedGraphNode> copiesDict 
                = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
                
        UndirectedGraphNode nodeCopy = new UndirectedGraphNode(node.label);
        copiesDict.put(node,nodeCopy);
        
        Queue<UndirectedGraphNode> q = new ArrayDeque<UndirectedGraphNode>();
        q.add(node);
        while(!q.isEmpty())
        {
            UndirectedGraphNode n = q.remove();
            UndirectedGraphNode nCopy = copiesDict.get(n);
            for(UndirectedGraphNode nodeToVisit: n.neighbors)
            {
                UndirectedGraphNode copy = copiesDict.get(nodeToVisit);
                if(copy == null)
                {
                    copy = new UndirectedGraphNode(nodeToVisit.label);
                    copiesDict.put(nodeToVisit, copy);
                    q.add(nodeToVisit);
                }
                nCopy.neighbors.add(copy);
            }
        }
        
        
        return nodeCopy;
    }
}

 

你可能感兴趣的:(133. Clone Graph)