[LeetCode]题解(python):133-Clone Graph
题目来源:
https://leetcode.com/problems/clone-graph/
题意分析:
克隆一个无向图。每个节点包括一个数值和它的邻居。
题目思路:
直接深度拷贝。
代码(python):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 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)