-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
36 lines (30 loc) · 1.11 KB
/
answer.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
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
#-------------------------------------------------------------------------------
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node:
return
copy = UndirectedGraphNode(node.label)
visited = {node: copy}
stack = [node]
while stack:
curr = stack.pop()
for n in curr.neighbors:
if n not in visited:
n_copy = UndirectedGraphNode(n.label)
visited[n] = n_copy
visited[curr].neighbors.append(n_copy)
stack.append(n)
else:
visited[curr].neighbors.append(visited[n])
return copy
#-------------------------------------------------------------------------------