首页 > 代码库 > [LeetCode]133 Clone Graph

[LeetCode]133 Clone Graph

https://oj.leetcode.com/problems/clone-graph/

http://blog.csdn.net/linhuanmars/article/details/22715747

/**
 * 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;
            
        UndirectedGraphNode copiedhead = new UndirectedGraphNode(node.label);

        Map<UndirectedGraphNode, UndirectedGraphNode> copiedmap = new HashMap<>();
        copiedmap.put(node, copiedhead);
        
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty())
        {
            UndirectedGraphNode oldnode = queue.poll();
            UndirectedGraphNode copiednode = copiedmap.get(oldnode);
            
            for (UndirectedGraphNode nei : oldnode.neighbors)
            {
                UndirectedGraphNode copiednei = copiedmap.get(nei);
                if (copiednei == null)
                {
                    // Copy
                    copiednei = new UndirectedGraphNode(nei.label);
                    copiedmap.put(nei, copiednei);
                    queue.offer(nei);
                }
                copiednode.neighbors.add(copiednei);
            }
        }

        return copiedhead;
    }
}




[LeetCode]133 Clone Graph