美文网首页
python实现leetcode之133. 克隆图

python实现leetcode之133. 克隆图

作者: 深圳都这么冷 | 来源:发表于2021-10-10 00:01 被阅读0次

解题思路

使用缓存记住已经计算过的,避免同一个对象拷贝多次
然后递归处理邻接节点
最后返回入口节点

133. 克隆图

代码

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val = 0, neighbors = []):
        self.val = val
        self.neighbors = neighbors
"""

class Solution(object):
    def __init__(self):
        self.cache = {}
    
    def cloneGraph(self, node):
        """
        :type node: Node
        :rtype: Node
        """
        if not node: return None
        if node.val not in self.cache:
            self.cache[node.val] = Node(val=node.val)
            neighbors = []
            for nb in node.neighbors:
                clone_nb = self.cloneGraph(nb)
                neighbors.append(clone_nb)
            self.cache[node.val].neighbors = neighbors
        return self.cache[node.val]
效果图

相关文章

  • LeetCode 133. 克隆图 | Python

    133. 克隆图 题目来源:力扣(LeetCode)https://leetcode-cn.com/problem...

  • python实现leetcode之133. 克隆图

    解题思路 使用缓存记住已经计算过的,避免同一个对象拷贝多次然后递归处理邻接节点最后返回入口节点 133. 克隆图[...

  • Leetcode图

    133. 克隆图[https://leetcode-cn.com/problems/clone-graph/] 2...

  • LeetCode-python 133. 克隆图

    题目链接[https://leetcode.cn/problems/clone-graph] 难度:中等 ...

  • LeetCode 力扣 133. 克隆图

    题目描述(中等难度) 复制一个图,图的节点定义如下。 neighbors 是一个装 Node 的 list ,因为...

  • LC吐血整理之Graph篇

    所有题解方法请移步 github-Leecode_summary 133. 克隆图 DFS&BFS 有整理过对象赋...

  • Python游戏开发,pgzrun模块,Python实现阿肯色克

    前言 利用Python实现Python和PyGameZero编写阿卡尼类(Outout)的克隆,废话不多说。 让我...

  • Leetcode133. 克隆图

    题目 给定无向连通图中一个节点的引用,返回该图的深拷贝(克隆)。图中的每个节点都包含它的值 val(Int) 和其...

  • LeetCode-133-克隆图

    克隆图 题目描述:给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。图中的每个节点都包含它的值 ...

  • ArrayList

    类图 实现了RandomAccess接口,可以随机访问 实现了Cloneable接口,可以克隆 实现了Serial...

网友评论

      本文标题:python实现leetcode之133. 克隆图

      本文链接:https://www.haomeiwen.com/subject/rysqoltx.html