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
  • 相关阅读:
    Python 基础之函数初识与函数参数
    python 基础之浅拷贝与深拷贝
    Python 基础之集合相关操作与函数和字典相关函数
    Python 基础之字符串操作,函数及格式化format
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
  • 原文地址:https://www.cnblogs.com/prmlab/p/7141207.html
Copyright © 2011-2022 走看看