我正在尝试将无向树划分为两个子树,每个子树都连接在一起。我的理解是,这可以使用此处描述的 Fiedler 矢量来完成。但是,当我遵循这个过程时,结果子树没有连接。
我用来实现二等分的代码如下,这里定义了不能二等分的树。
import networkx as nx
from itertools import compress
g = nx.from_dict_of_dicts(broken_g)
def split_graph(graph):
"""Split a graph into two pieces using the Fiedler vector.
See https://en.wikipedia.org/wiki/Graph_partition#Fiedler_eigenvalue_and_eigenvector
"""
assert nx.is_connected(graph), 'must pass connected graph'
fiedler_vec = nx.fiedler_vector(graph, normalized=True, weight=False)
mask_a = fiedler_vec > 0
mask_b = ~ mask_a
subgraph_a_nodes = compress(graph.nodes(), mask_a)
subgraph_b_nodes = compress(graph.nodes(), mask_b)
subgraph_a = graph.subgraph(subgraph_a_nodes)
subgraph_b = graph.subgraph(subgraph_b_nodes)
assert nx.is_connected(subgraph_a) and nx.is_connected(subgraph_b), 'split did not produce connected subgraphs'
return [subgraph_a, subgraph_b]
split_graph(g)
当我运行它时,结果子树都没有连接 - 每个子树都有一个或两个大的连接组件和几个孤立的节点。绘制 Fiedler 向量的值并识别孤立节点如下所示:
这到底是怎么回事?