Skip to content

Commit 7f8e859

Browse files
committed
add solution: clone-graph
1 parent 53236d2 commit 7f8e859

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

clone-graph/dusunax.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
# 133. Clone Graph
3+
This is the problem for copying nodes, which helps you understand the concept of referencing a node & copying the node (creating a new node from the existing one).
4+
5+
👉 Perform recursion DFS with the correct escape condition and handling of NoneType.
6+
'''
7+
8+
"""
9+
# Definition for a Node.
10+
class Node:
11+
def __init__(self, val = 0, neighbors = None):
12+
self.val = val
13+
self.neighbors = neighbors if neighbors is not None else []
14+
"""
15+
from typing import Optional
16+
class Solution:
17+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
18+
if node is None:
19+
return None
20+
21+
visited = {}
22+
23+
def DFS(currNode):
24+
if currNode.val in visited:
25+
return visited[currNode.val]
26+
27+
copiedNode = Node(currNode.val)
28+
visited[currNode.val] = copiedNode
29+
30+
for neighbor in currNode.neighbors:
31+
copiedNode.neighbors.append(DFS(neighbor))
32+
33+
return copiedNode
34+
35+
return DFS(node)

0 commit comments

Comments
 (0)