forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdusunax.py
35 lines (27 loc) Β· 1.02 KB
/
dusunax.py
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
'''
# 133. Clone Graph
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).
π Perform recursion DFS with the correct escape condition and handling of NoneType.
'''
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if node is None:
return None
visited = {}
def DFS(currNode):
if currNode.val in visited:
return visited[currNode.val]
copiedNode = Node(currNode.val)
visited[currNode.val] = copiedNode
for neighbor in currNode.neighbors:
copiedNode.neighbors.append(DFS(neighbor))
return copiedNode
return DFS(node)