-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathClone_Graph_BFS.py
More file actions
94 lines (66 loc) · 2.26 KB
/
Clone_Graph_BFS.py
File metadata and controls
94 lines (66 loc) · 2.26 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
# Example Input:
# 1 <---> 2
# ^ ^
# | |
# v v
# 4 <---> 3
# Example Output:
# 1 <---> 2
# ^ ^
# | |
# v v
# 4 <---> 3
def clone(node):
queue = []
visited = {}
queue.append(node)
while len(queue) > 0:
cur = queue.pop(0)
new_node = None
# if current node was visitied we must have created a clone of it so
## we retrieve it and call it new_node otherwise we create it from scratch by calling Node class
if cur in visited.keys():
new_node = visited[cur]
else:
## if this clone is newly created we need to update the visited dictionary
new_node = Node(cur.val, [])
visited[cur] = new_node
## Neighbors of the clone of current node
neighbors = new_node.neighbors
# now iterate over current node neighors
for i in range(len(cur.neighbors)):
## if for some of the neighbors we have already created clones
## then we append them to the neighbors of the new clone (new_node.neighbors or neighbors)
if cur.neighbors[i] in visited.keys():
neighbors.append(visited[cur.neighbors[i]])
else:
## otherwise we append neighbors to the queue
queue.append(cur.neighbors[i])
## and we clone the neighbors and append to the new clone neighbors
## and mark them as in the visited dictionary
new_neighbor_node = Node(cur.neighbors[i].val, [])
neighbors.append(new_neighbor_node)
visited[cur.neighbors[i]] = new_neighbor_node
return visited[node]
node = Node(1, [])
node2 = Node(2, [])
node3 = Node(3, [])
node4 = Node(4, [])
node.neighbors.append(node2)
node.neighbors.append(node4)
node2.neighbors.append(node)
node2.neighbors.append(node3)
node3.neighbors.append(node2)
node3.neighbors.append(node4)
node4.neighbors.append(node)
node4.neighbors.append(node3)
b=clone(node)
node2_new,node4_new=[ne for ne in b.neighbors]
[ne.val for ne in node4_new.neighbors]
[1, 3]
[ne.val for ne in node4_new.neighbors]
[1, 3]