克隆一张无向图,图中的每个节点包含一个 label (标签)和一个 neighbors (邻接点)列表 。
OJ的无向图序列化:
节点被唯一标记。
我们用 # 作为每个节点的分隔符,用 , 作为节点标签和邻接点的分隔符。
例如,序列化无向图 {0,1,2#1,2#2,2}。
该图总共有三个节点, 被两个分隔符 # 分为三部分。
第一个节点的标签为 0,存在从节点 0 到节点 1 和节点 2 的两条边。
第二个节点的标签为 1,存在从节点 1 到节点 2 的一条边。
第三个节点的标签为 2,存在从节点 2 到节点 2 (本身) 的一条边,从而形成自环。
我们将图形可视化如下:
1
/ \
/ \
0 --- 2
/ \
\_/
解题思路:
将图结构用邻接表表示:
labels | neighbors |
---|---|
0 | 1,2 |
1 | 2 |
2 | 2 |
建立一个哈希表:<图中的label,根据图中的label建立的节点>
建立一个栈,栈顶存储遍历的节点。
深度优先遍历这个图:弹出栈的一个元素,对于弹出的节点,遍历这个节点的neighbors。对于每一个邻接节点的neighbor元素。将其加入栈中。判断每一个neighbor是否在哈希表,如果不在就加入哈希表中。对于哈希表的每一个元素,添加它的邻接节点neighbors.
# 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 None
quene = [node]
visit = dict()
root = UndirectedGraphNode(node.label)
visit[node.label] = root
while quene:
top = quene.pop()
for n in top.neighbors:
if n.label not in visit:
quene.append(n)
visit[n.label] = UndirectedGraphNode(n.label)
visit[top.label].neighbors.append(visit[n.label])
return root