Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use# as a separator for each node, and , as
a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
There are two solutions for this problem both based on BFS
one iterative another recursive.
The time complexity if O(V+E) and space is the same.
we need to maintain the que.
1. Recursive:
# 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 __init__(self):
self.dict={None:None}
def cloneGraph(self, node):
if node==None:
return None
head=UndirectedGraphNode(node.label)
self.dict[node]=head
for n in node.neighbors:
if n in self.dict:
head.neighbors.append(self.dict[n])
else:
neigh=self.cloneGraph(n)
head.neighbors.append(neigh)
return head
For iterative solution.
It looks more intuitive.
# 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 node==None:
return node
que=[node]
head=UndirectedGraphNode(node.label)
dict={node:head}
while que:
curr=que.pop(0)
for n in curr.neighbors:
if n in dict:
dict[curr].neighbors.append(dict[n])
else:
que.append(n)
copy=UndirectedGraphNode(n.label)
dict[n]=copy
dict[curr].neighbors.append(copy)
return head
克隆无向图算法
本文介绍了一种基于广度优先搜索(BFS)的无向图克隆算法,包括递归和迭代两种实现方式。该算法的时间复杂度为O(V+E),其中V表示顶点数,E表示边数。文章提供了Python代码示例,并解释了如何通过维护节点字典来避免重复克隆。
325

被折叠的 条评论
为什么被折叠?



