-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0133_Clone_Graph.py
More file actions
38 lines (33 loc) · 1.19 KB
/
Copy path0133_Clone_Graph.py
File metadata and controls
38 lines (33 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = neighbors
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
'''Stack iterative solution'''
if not node:
return None
visited = {node: Node(node.val)}
stack = [node]
head = node
while stack:
node = stack.pop()
for neighbor in node.neighbors:
if neighbor not in visited:
stack.append(neighbor)
visited[neighbor] = Node(neighbor.val)
visited[node].neighbors.append(visited[neighbor])
return visited[head]
'''Recursion solution'''
# visited = {}
# def clone_graph(node, visited):
# if not node:
# return None
# if node in visited:
# return visited[node]
# new_node = Node(node.val)
# visited[node] = new_node
# new_node.neighbors = [clone_graph(neighbor, visited) for neighbor in node.neighbors]
# return new_node
# return clone_graph(node, visited)