首页 > 代码库 > 133. Clone Graph
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 #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(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
133. Clone Graph