133. Clone Graph
Posted 蜃利的阴影下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章