码迷,mamicode.com
首页 > 其他好文 > 详细

133. Clone Graph (Graph)

时间:2018-08-17 00:32:52      阅读:191      评论:0      收藏:0      [点我收藏+]

标签: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实际代码

注意事项已标注

133. Clone Graph (Graph)

标签:dir   put   nta   new   copy   public   enc   clone   for   

原文地址:https://www.cnblogs.com/goPanama/p/9490873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!