[LeetCode]题解(python):133-Clone Graph

Posted Ry_Chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):133-Clone Graph相关的知识,希望对你有一定的参考价值。

题目来源:

  https://leetcode.com/problems/clone-graph/


 

题意分析:

  克隆一个无向图。每个节点包括一个数值和它的邻居。


 

题目思路:

  直接深度拷贝。


 

代码(python):

  

# Definition for a undirected graph node
# class UndirectedGraphNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

class Solution(object):
    def cloneGraph(self, node):
        """
        :type node: UndirectedGraphNode
        :rtype: UndirectedGraphNode
        """
        if node == None:
            return node
        d  = {}
        def dfs(n):
            if n in d:
                return d[n]
            ans = UndirectedGraphNode(n.label)
            d[n] = ans
            for i in n.neighbors:
                ans.neighbors.append(dfs(i))
            return ans
        return dfs(node)
View Code

 

以上是关于[LeetCode]题解(python):133-Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode第133题—克隆图—Python实现

《LeetCode之每日一题》:133.删除链表中的节点

[LeetCode]题解(python):100 Same Tree

[LeetCode]题解(python):112 Path Sum

[LeetCode] 133. Clone Graph

[LeetCode]题解(python):101-Symmetric Tree