我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/clone-graph/description/
题目描述:
知识点:深度优先遍历、广度优先遍历
思路一:深度优先遍历
用一个哈希表hashMap来记录已经克隆了的节点,深度优先遍历的递归函数实现如下:
(1)如果node节点本身为null,直接返回null。
(2)如果hashMap中已经存在了node.label对应的节点,直接返回该节点即可。
(3)如果hashMap中还没有存在node.label对应的节点,新建一个节点,其label值为node.label,其neighbors的填充,需要遍历node.neighbors中的每一个节点,递归地调用该函数来填充。最后,返回cloned。
时间复杂度与每个节点所连接的节点个数有关。空间复杂度为O(n),其中n为节点个数。
JAVA代码:
public class Solution {
private HashMap<Integer, UndirectedGraphNode> hashMap = new HashMap<>(); //记录已克隆的节点
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(null == node){
return null;
}
UndirectedGraphNode cloned = hashMap.get(node.label);
if(null != cloned){
return cloned;
}
cloned = new UndirectedGraphNode(node.label);
hashMap.put(cloned.label, cloned);
for(UndirectedGraphNode neighbor : node.neighbors){
cloned.neighbors.add(cloneGraph(neighbor));
}
return cloned;
}
}
LeetCode解题报告:
思路二:广度优先遍历
和思路一一样,用一个hashMap记录已克隆的节点,利用队列实现广度优先遍历。
出队入队操作的是原图中的节点,对于出队入队的循环过程,应该如下:
(1)弹出队首元素now,而得到的克隆节点应该是从hashMap中根据now.label得到的节点。
(2)遍历now的所有邻接点,如果hashMap中还不存在键为neighbor.label的节点,则将该节点入队,且在hashMap中新建label为neighbor.label的节点。不管怎样,都需要将hashMap中键为neighbor.label的节点放进cloned的neighbors中。
最后返回的是root节点,即从hashMap中取得的键为node.label的节点。
时间复杂度与每个节点所连接的节点个数有关。空间复杂度为O(n),其中n为节点个数。
JAVA代码:
public class Solution {
private HashMap<Integer, UndirectedGraphNode> hashMap = new HashMap<>(); //记录已克隆的节点
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(null == node){
return null;
}
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.add(node);
hashMap.put(node.label, new UndirectedGraphNode(node.label));
UndirectedGraphNode root = hashMap.get(node.label);
while(!queue.isEmpty()){
UndirectedGraphNode now = queue.poll();
UndirectedGraphNode cloned = hashMap.get(now.label);
for(UndirectedGraphNode neighbor : now.neighbors){
if(!hashMap.containsKey(neighbor.label)){
queue.add(neighbor);
hashMap.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
}
cloned.neighbors.add(hashMap.get(neighbor.label));
}
}
return root;
}
}
LeetCode解题报告: