码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]133 Clone Graph

时间:2015-01-09 01:53:41      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600749

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!