133. Clone Graph
Posted 我的名字叫周周
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了133. Clone Graph相关的知识,希望对你有一定的参考价值。
/* * 133. Clone Graph * 12.19 by Mingyang * 第一种方法就是我们用的那种BFS的方法,queue进行广度遍历 * 不要忘了新建neighbor的点后要注意把关系也copy过来 * 第二种方法就是DFS的方法,也就是stack来做深度遍历,换汤不换药 * 无论怎么换,记住,用map比较好,可以记住两个node之间的对应关系 */ public UndirectedGraphNode cloneGraph(UndirectedGraphNode root) { if (root == null) return null; Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); queue.add(root); map.put(root, new UndirectedGraphNode(root.label)); while (!queue.isEmpty()) { UndirectedGraphNode node = queue.poll(); // handle the neighbors for (UndirectedGraphNode neighbor : node.neighbors) { if (!map.containsKey(neighbor)) { map.put(neighbor, new UndirectedGraphNode(neighbor.label)); // 这就是一个映射的影子,对于每一个元素,在地图中注册下你的影子 queue.add(neighbor); } // copy the neighbor map.get(node).neighbors.add(map.get(neighbor)); // 当注册好影子以后,我们需要把原图中的关系也copy过来 } } return map.get(root); } // 用非递归的DFS来做,也就是用Stack public UndirectedGraphNode cloneGraph2(UndirectedGraphNode root) { if (root == null) return null; HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); LinkedList<UndirectedGraphNode> stack = new LinkedList<UndirectedGraphNode>(); UndirectedGraphNode head = new UndirectedGraphNode(root.label); map.put(root, head); stack.push(root); while (!stack.isEmpty()) { UndirectedGraphNode node = stack.pop(); for (UndirectedGraphNode neighbor : node.neighbors) { if (!map.containsKey(neighbor)) { map.put(neighbor, new UndirectedGraphNode(neighbor.label)); stack.push(neighbor); } map.get(node).neighbors.add(map.get(neighbor)); } } return head; } //用递归的DFS public UndirectedGraphNode cloneGraph3(UndirectedGraphNode node) { if(node == null) return null; HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); UndirectedGraphNode head = new UndirectedGraphNode(node.label); map.put(node, new UndirectedGraphNode(node.label)); dfs(map, node);//DFS return head; } public void dfs(HashMap<UndirectedGraphNode, UndirectedGraphNode> map, UndirectedGraphNode node){ if(node == null) return; for(UndirectedGraphNode neighbor: node.neighbors){ if(!map.containsKey(neighbor)){ map.put(neighbor, new UndirectedGraphNode(neighbor.label)); dfs(map, neighbor);//DFS } map.get(node).neighbors.add(map.get(neighbor)); } }
以上是关于133. Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章