Thursday, September 18, 2014

Leetcode: Clone Graph @Python

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

class Solution:
    # @param node, a undirected graph node
    # @return a undirected graph node
    # dps
    def cloneGraph(self, node):
        if not node: return None
        def dfs(input, dic):
            if input in dic: return dic[input]
            newnode=UndirectedGraphNode(input.label)
            dic[input]=newnode
            for neighbor in input.neighbors:
                newnode.neighbors.append(dfs(neighbor,dic))
            return newnode
        return dfs(node,{})

No comments :

Post a Comment