首页 > 编程语言> > Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors. OJ
Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors. OJ
作者:互联网
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * ArrayList<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ import java.util.*; public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null ){ return null; } Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>(); return clone(node,map); } public UndirectedGraphNode clone(UndirectedGraphNode node, Map<UndirectedGraphNode,UndirectedGraphNode> map){ if(node == null){ return null; } if(map.containsKey(node)){ return map.get(node); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(node,newNode); for(UndirectedGraphNode n : node.neighbors){ newNode.neighbors.add(clone(n,map)); } return newNode; } }
标签:node,UndirectedGraphNode,null,return,map,graph,undirected 来源: https://www.cnblogs.com/q-1993/p/11332560.html