zoukankan      html  css  js  c++  java
  • 133. Clone Graph

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.


    OJ's undirected graph serialization:

    Nodes are labeled uniquely.

    We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

    As an example, consider the serialized graph {0,1,2#1,2#2,2}.

    The graph has a total of three nodes, and therefore contains three parts as separated by #.

    1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
    2. Second node is labeled as 1. Connect node 1 to node 2.
    3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

    Visually, the graph looks like the following:

           1
          / 
         /   
        0 --- 2
             / 
             \_/
    

    Sol :

    Quick recap how to implement DFS. 

    http://www.cnblogs.com/prmlab/p/6905926.html

    The implementation below uses the stack data-structure to build-up and return a set of vertices that are accessible within the subjects connected component. Using Python’s overloading of the subtraction operator to remove items from a set, we are able to add only the unvisited adjacent vertices.

    def dfs(graph, start, visited=None):
        if visited is None:
            visited = set()
        visited.add(start)
        for nxt in graph[start] - visited:
            dfs(graph, nxt, visited)
        return visited
    
    dfs(graph, 'A')
    {'A', 'B', 'C', 'D', 'E', 'F'}


     

    The second implementation provides the same functionality as the first, however, this time we are using the more succinct recursive form. Due to a common Python gotcha with default parameter values being created only once, we are required to create a new visited set on each user invocation. Another Python language detail is that function variables are passed by reference, resulting in the visited mutable set not having to reassigned upon each recursive call.

    def dfs(graph, start, visited=None):
        if visited is None:
            visited = set()
        visited.add(start)
        for nxt in graph[start] - visited:
            dfs(graph, nxt, visited)
        return visited
    
    dfs(graph, 'A')
    {'A', 'B', 'C', 'D', 'E', 'F'}   






    READY TO GO!


    # 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
        
        
        def __init__(self):
            self.visited = {}
            
        def cloneGraph(self, node):
            if not node:
                return None
            
            # the problem wants us to "return a undirected graph node", the following two lines are the doing this
            if node.label in self.visited:
                return self.visited[node.label]
    
            # add label to clone regradless visited or not 
            clone = UndirectedGraphNode(node.label)
            self.visited[node.label] = clone
                
            # call this function recursively to append neighbors
            for n in node.neighbors:
                clone.neighbors.append(self.cloneGraph(n))
            return clone
  • 相关阅读:
    测试工作中需要用到的一些linux命令
    软件的性能测试到底是测试哪些方面
    软件测试中的安全测试包括哪些方面
    git一不小心上传了大文件,怎么破?
    接口测试校验返回数据格式,JasonSchema使用详解
    selenium定位中需要鼠标悬浮才能显示的按钮
    jenknis参数化构建,windows和shell引用变量
    selenium元素定位之父子节点、胞节点
    selenium元素定位之多个元素中选择其中的一个
    Python实现注册和三次验证登录
  • 原文地址:https://www.cnblogs.com/prmlab/p/7141207.html
Copyright © 2011-2022 走看看