133. Clone Graph (Graph)

 1 class Solution {
 2     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
 3         Map map = new HashMap<>();
 4         return dfs(node, map);   
 5     }
 6     
 7     
 8     public UndirectedGraphNode dfs(UndirectedGraphNode node, Map 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实际代码

注意事项已标注

转载于:https://www.cnblogs.com/goPanama/p/9490873.html

你可能感兴趣的:(133. Clone Graph (Graph))