Skip to content

Commit 34c4e88

Browse files
committed
- Clone Graph DaleStudy#259
1 parent 6dcc211 commit 34c4e88

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

clone-graph/ayosecu.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from typing import Optional
2+
from collections import deque
3+
4+
# Definition for a Node.
5+
class Node:
6+
def __init__(self, val = 0, neighbors = None):
7+
self.val = val
8+
self.neighbors = neighbors if neighbors is not None else []
9+
10+
class Solution:
11+
"""
12+
- Time Complexity: O(N + E)
13+
- N = The number of nodes
14+
- E = The number of neighbors
15+
- Space Complexity: O(N + E)
16+
"""
17+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
18+
if not node:
19+
return None
20+
21+
dq = deque([node])
22+
dic = {}
23+
dic[node] = Node(node.val)
24+
25+
while dq:
26+
pop_node = dq.popleft()
27+
28+
for n in pop_node.neighbors:
29+
if n not in dic:
30+
dq.append(n)
31+
dic[n] = Node(n.val)
32+
dic[pop_node].neighbors.append(dic[n])
33+
34+
return dic[node]
35+
36+
37+
### TEST CASES ###
38+
def build_graph(adj_list):
39+
if not adj_list:
40+
return None
41+
42+
nodes = {}
43+
for i in range(1, len(adj_list) + 1):
44+
nodes[i] = Node(i)
45+
46+
for i, neighbors in enumerate(adj_list, 1):
47+
nodes[i].neighbors = [nodes[n] for n in neighbors]
48+
49+
return nodes[1]
50+
51+
52+
def print_graph(node):
53+
if not node:
54+
print("None")
55+
return
56+
57+
visited = set()
58+
q = deque([node])
59+
while q:
60+
curr = q.popleft()
61+
if curr in visited:
62+
continue
63+
visited.add(curr)
64+
print(f"Node {curr.val}: {[n.val for n in curr.neighbors]}")
65+
for neighbor in curr.neighbors:
66+
if neighbor not in visited:
67+
q.append(neighbor)
68+
69+
tc = [
70+
[[2,4],[1,3],[2,4],[1,3]],
71+
[[]],
72+
[]
73+
]
74+
75+
sol = Solution()
76+
for i, adj_list in enumerate(tc, 1):
77+
original = build_graph(adj_list)
78+
print(f"===== TC {i} =====")
79+
print("Original Graph:")
80+
print_graph(original)
81+
82+
cloned = sol.cloneGraph(original)
83+
84+
print("\nCloned Graph:")
85+
print_graph(cloned)

0 commit comments

Comments
 (0)