Clone Graph,采用BFS,同时用一个Map记录原先节点和现在节点的映射,顺便可以用来做visited check。一开始有两个错误,一是null的时候也要返回null,二是有可能节点0也有指向0本身的邻居,所以在对neighbors做遍历前要先放到map里。
public class Solution { HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { map.clear(); return cloneNode(node); } private UndirectedGraphNode cloneNode(UndirectedGraphNode node) { if (node == null) return null; if (map.containsKey(node)) return map.get(node); else { UndirectedGraphNode copy = new UndirectedGraphNode(node.label); map.put(node, copy); for (UndirectedGraphNode n : node.neighbors) { copy.neighbors.add(cloneNode(n)); } return copy; } } }