leetcode Clone Graph

本文介绍了一种使用深度优先遍历实现无向图克隆的方法。通过递归方式,确保每个节点及其邻居被正确复制,并保持原有的连接关系。

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

题目链接

这个题目就是用深度优先遍历就好。但是记录方式要更改一下。并不是那个点已经访问过就直接返回。因为一个点可以重复链接自己,也可重复链接别人

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
   HashMap<Integer,UndirectedGraphNode> record=new HashMap<>();
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null)
        {
            return node;
        }
        UndirectedGraphNode result=new UndirectedGraphNode(node.label);
        record.put(node.label,result);

        for(UndirectedGraphNode niber:node.neighbors)
        {

            help(result,niber);

        }

        return result;

    }


    public void help(UndirectedGraphNode father,UndirectedGraphNode ori)
    {
        UndirectedGraphNode newNode=record.get(ori.label);
        if(newNode!=null)
        {
            father.neighbors.add(newNode);
            return;
        }
        newNode=new UndirectedGraphNode(ori.label);
        record.put(ori.label,newNode);

        father.neighbors.add(newNode);

        for(UndirectedGraphNode niber:ori.neighbors)
        {
            help(newNode,niber);

        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值