LeetCode133——克隆图

本文详细解析了LeetCode上“Clone Graph”问题的两种解法:深度优先遍历和广度优先遍历。通过使用哈希表记录已克隆节点,避免重复克隆,实现了图的深拷贝。提供了完整的JAVA代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的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解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值