Leetcode 133. Clone Graph

本文介绍了一种基于递归的图深拷贝算法实现。该算法适用于无向图的节点复制,通过创建新节点并复制原始节点的邻居列表来完成图的深拷贝。文章中的代码示例使用Python编写。

Problem

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 value (int) and a list (List[Node]) of its neighbors.

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

Test case format:

For simplicity, 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.

An 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.

Algorithm

Recursion.

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []
"""

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        
        if not node:
            return None
        
        save = [None] * 101
        def graphDeepCopy(node):
            nonlocal save
            new= Node(node.val)
            save[node.val] = new
            for neighbor in node.neighbors:
                if save[neighbor.val]:
                    neighbor_node = save[neighbor.val]
                else:
                    neighbor_node = graphDeepCopy(neighbor)
                new.neighbors.append(neighbor_node)
            return new
        
        return graphDeepCopy(node)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值