Skip to content

Commit 42b5637

Browse files
authored
Create Clone Graph.py
1 parent 4ccfd66 commit 42b5637

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Clone Graph.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'''
2+
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
3+
4+
OJ's undirected graph serialization:
5+
6+
Nodes are labeled uniquely.
7+
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
8+
9+
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
10+
11+
The graph has a total of three nodes, and therefore contains three parts as separated by #.
12+
13+
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
14+
Second node is labeled as 1. Connect node 1 to node 2.
15+
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
16+
17+
Visually, the graph looks like the following:
18+
19+
1
20+
/ \
21+
/ \
22+
0 --- 2
23+
/ \
24+
\_/
25+
26+
'''
27+
28+
# Definition for a undirected graph node
29+
# class UndirectedGraphNode:
30+
# def __init__(self, x):
31+
# self.label = x
32+
# self.neighbors = []
33+
34+
class Solution:
35+
# @param node, a undirected graph node
36+
# @return a undirected graph node
37+
def cloneGraph(self, node):
38+
if not node:
39+
return None
40+
41+
dic = {}
42+
mirror = UndirectedGraphNode(node.label)
43+
dic[node] = mirror
44+
45+
vec = [node]
46+
visited = set([node])
47+
while vec:
48+
tmp = vec.pop()
49+
for neighbor in tmp.neighbors:
50+
if neighbor not in dic:
51+
mirror = UndirectedGraphNode(neighbor.label)
52+
dic[neighbor] = mirror
53+
54+
dic[tmp].neighbors.append(dic[neighbor])
55+
56+
if neighbor not in visited:
57+
visited.add(neighbor)
58+
vec.append(neighbor)
59+
60+
return dic[node]
61+

0 commit comments

Comments
 (0)