1. 程式人生 > >133. Clone Graph (Graph)

133. Clone Graph (Graph)

contains .get ret turn contain pan label graph for

 1 class Solution {
 2     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
 3         Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
 4         return dfs(node, map);   
 5     }
 6     
 7     
 8     public UndirectedGraphNode dfs(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
9 if(node == null) return null; 10 UndirectedGraphNode clone = new UndirectedGraphNode(node.label); 11 12 map.put(node, clone); //每遍歷一個node 要在map中記錄已經遍歷過 13 14 for(UndirectedGraphNode n : node.neighbors) { 15 if(map.containsKey(n)) { 16 clone.neighbors.add(map.get(n)); //
如果不用map.get(n),直接用n的話 是add原來node的reference就不是copy 17 }else { 18 clone.neighbors.add(dfs(n, map)); 19 20 } 21 } 22 return clone; 23 } 24 }

初次了解DFS實際代碼

註意事項已標註

133. Clone Graph (Graph)