标签:dir put nta new copy public enc clone 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实际代码
注意事项已标注
标签:dir put nta new copy public enc clone for
原文地址:https://www.cnblogs.com/goPanama/p/9490873.html