133. Clone Graph (Graph)
Posted gopanama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了133. Clone Graph (Graph)相关的知识,希望对你有一定的参考价值。
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)的主要内容,如果未能解决你的问题,请参考以下文章