图
一 克隆图
广搜
133 Clone Graph
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) return node; LinkedList<UndirectedGraphNode> queue = new LinkedList<>(); HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>(); queue.offer(node); UndirectedGraphNode copy = new UndirectedGraphNode(node.label); map.put(node, copy); while (!queue.isEmpty()){ UndirectedGraphNode cur = queue.poll(); for (int i = 0; i < cur.neighbors.size(); i++){ if (!map.containsKey(cur.neighbors.get(i))){ copy = new UndirectedGraphNode(cur.neighbors.get(i).label); map.put(cur.neighbors.get(i), copy); queue.offer(cur.neighbors.get(i)); } map.get(cur).neighbors.add(map.get(cur.neighbors.get(i))); } } return map.get(node); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) return node; LinkedList<UndirectedGraphNode> stack = new LinkedList<>(); HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>(); stack.push(node); UndirectedGraphNode copy = new UndirectedGraphNode(node.label); map.put(node, copy); while (!stack.isEmpty()){ UndirectedGraphNode cur = stack.poll(); for (int i = 0; i < cur.neighbors.size(); i++){ if(!map.containsKey(cur.neighbors.get(i))){ copy = new UndirectedGraphNode(cur.neighbors.get(i).label); map.put(cur.neighbors.get(i), copy); stack.push(cur.neighbors.get(i)); } map.get(cur).neighbors.add(map.get(cur.neighbors.get(i))); } } return map.get(node); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) return null; HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); UndirectedGraphNode copy = new UndirectedGraphNode(node.label); map.put(node,copy); helper(node,map); return copy; } private void helper(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map) { for(int i=0;i<node.neighbors.size();i++) { UndirectedGraphNode cur = node.neighbors.get(i); if(!map.containsKey(cur)) { UndirectedGraphNode copy = new UndirectedGraphNode(cur.label); map.put(cur,copy); helper(cur,map); } map.get(node).neighbors.add(map.get(cur)); } }