-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path133.clone-graph.py
More file actions
41 lines (31 loc) · 926 Bytes
/
133.clone-graph.py
File metadata and controls
41 lines (31 loc) · 926 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
33
34
35
36
37
38
39
40
#
# @lc app=leetcode id=133 lang=python
#
# [133] Clone Graph
#
# @lc code=start
# Definition for a Node.
""" class Node(object):
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else [] """
class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
if not node:
return None
visited = {node: Node(node.val)}
stack = [node]
head = visited[node]
while stack:
current = stack.pop()
for neighbor in current.neighbors:
if neighbor not in visited:
visited[neighbor] = Node(neighbor.val)
stack.append(neighbor)
visited[current].neighbors.append(visited[neighbor])
return head
# @lc code=end