133. Clone Graph
一、题目
1、审题
2、分析
深度复制一个图的结构。
二、解答
1、思路:
采用一个 Map 存储新建的图的节点值、对应的节点。
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { return clone(node); } private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>(); private UndirectedGraphNode clone(UndirectedGraphNode node) { if(node == null) return null; if(map.containsKey(node.label)) return map.get(node.label); UndirectedGraphNode clone = new UndirectedGraphNode(node.label); map.put(clone.label, clone); for(UndirectedGraphNode neighbor: node.neighbors) clone.neighbors.add(clone(neighbor)); return clone; }