-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloneGraph.py
More file actions
32 lines (29 loc) · 889 Bytes
/
Copy pathcloneGraph.py
File metadata and controls
32 lines (29 loc) · 889 Bytes
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
#!/user/bin/env python3
# coding=utf-8
"""
@project : algorithmPython
@ide : PyCharm
@file : cloneGraph
@author : illusion
@desc : 133. 克隆图 https://leetcode-cn.com/problems/clone-graph/
@create : 2021/6/5
"""
# 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 []
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None:
return None
visited = {}
return self.dfs(node, visited)
def dfs(self, node: 'Node', visited):
if node in visited:
return visited[node]
new_node = Node(val=node.val)
visited[node] = new_node
for neighbor in node.neighbors:
new_node.neighbors.append(self.dfs(neighbor, visited))
return new_node