首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。