LeetCode 133. Clone Graph 克隆图(Java)

题目:

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Test case format:
For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.
Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
在这里插入图片描述
在这里插入图片描述
Constraints:

  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
  • Number of Nodes will not exceed 100.
  • There is no repeated edges and no self-loops in the graph.
  • The Graph is connected and all nodes can be visited starting from the given node.

解答:

题目本身的意思比较不容易理解,要求我们复制一个图,对原图进行深拷贝。
其中,深拷贝指的是,对一个节点进行深拷贝,则必须生成一个新的节点,这个节点的所有属性值与原节点相同,但这两个节点在内存中,是两个不同的对象。

所以解题思路为采用深度优先遍历

  1. 为避免重复拷贝,建立一个HashMap,使用哈希表来存储原 node 和新 node 的对应关系
  2. 若 node 节点本身为null,直接返回null
  3. 遍历 node 的每个邻居节点,若 HashMap中已经存在了对应的邻居节点,则直接获得它的拷贝
  4. 若 HashMap 中还没存在对应的邻居节点,则递归调用函数进行填充(即将拷贝节点放入Hashmap中,并且使得新 node 的邻接链表添加原 node 的邻接链表里的元素)

具体代码实现如下:

class Solution {
    HashMap<Node, Node> map = new HashMap<>();
    public Node cloneGraph(Node node) {
        if(node == null) return null;
        Node copy = new Node(node.val, new ArrayList<>());
        map.put(node, copy);
        for(Node neighbor : node.neighbors){
            if(map.containsKey(neighbor)){
                copy.neighbors.add(map.get(neighbor));
            }else{
                copy.neighbors.add(cloneGraph(neighbor));
            }
        }
        return copy;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值