File tree Expand file tree Collapse file tree 2 files changed +84
-0
lines changed
Expand file tree Collapse file tree 2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Clone an undirected graph. Each node in the graph contains a label and a list
3+ of its neighbors.
4+ """
5+
6+ # Definition for a undirected graph node
7+ # class UndirectedGraphNode(object):
8+ # def __init__(self, x):
9+ # self.label = x
10+ # self.neighbors = []
11+
12+ class Solution (object ):
13+ def cloneGraph (self , node ):
14+ """
15+ :type node: UndirectedGraphNode
16+ :rtype: UndirectedGraphNode
17+
18+ BFS
19+ """
20+ if node is None :
21+ return None
22+ queue = []
23+ start_cloned_node = UndirectedGraphNode (node .label )
24+ visited = set ()
25+ # A dictionary that maps labels to cloned nodes
26+ d = {node : start_cloned_node }
27+ queue .append (node )
28+ while queue :
29+ node = queue .pop (0 )
30+ visited .add (node )
31+ cloned_node = d [node ]
32+ cloned_neighbors = []
33+ for neighbor in node .neighbors :
34+ if neighbor not in visited :
35+ queue .append (neighbor )
36+ if neighbor not in d :
37+ cloned_neighbor = UndirectedGraphNode (neighbor .label )
38+ d [neighbor ] = cloned_neighbor
39+ else :
40+ cloned_neighbor = d [neighbor ]
41+ cloned_neighbors .append (cloned_neighbor )
42+ cloned_node .neighbors = cloned_neighbors
43+ return start_cloned_node
Original file line number Diff line number Diff line change 1+ """
2+ Clone an undirected graph. Each node in the graph contains a label and a list
3+ of its neighbors.
4+ """
5+
6+ # Definition for a undirected graph node
7+ # class UndirectedGraphNode(object):
8+ # def __init__(self, x):
9+ # self.label = x
10+ # self.neighbors = []
11+
12+ class Solution (object ):
13+ def cloneGraph (self , node ):
14+ """
15+ :type node: UndirectedGraphNode
16+ :rtype: UndirectedGraphNode
17+
18+ DFS
19+ """
20+ if node is None :
21+ return None
22+ self .visited = set ()
23+ cloned_node = UndirectedGraphNode (node .label )
24+ self .d = {node : cloned_node }
25+ self .visit (node )
26+ return self .d [node ]
27+
28+ def visit (self , node ):
29+ if node not in self .visited :
30+ self .visited .add (node )
31+ cloned_node = self .d [node ]
32+ cloned_neighbors = []
33+ for neighbor in node .neighbors :
34+ if neighbor not in self .d :
35+ cloned_neighbor = UndirectedGraphNode (neighbor .label )
36+ self .d [neighbor ] = cloned_neighbor
37+ else :
38+ cloned_neighbor = self .d [neighbor ]
39+ cloned_neighbors .append (cloned_neighbor )
40+ self .visit (neighbor )
41+ cloned_node .neighbors = cloned_neighbors
You can’t perform that action at this time.
0 commit comments