码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-04-05 15:33:21      阅读:451      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  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

标签:

原文地址:http://www.cnblogs.com/chruny/p/5354816.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!