注意
转到末尾 以下载完整的示例代码。
通过最大流实现的最大二分匹配
这个例子展示了如何使用最大流来可视化二分匹配(参见 igraph.Graph.maxflow())。
注意
igraph.Graph.maximum_bipartite_matching() 通常是找到最大二分匹配的更好方法。要了解如何使用该方法,请查看 最大二分匹配。
import igraph as ig
import matplotlib.pyplot as plt
我们首先创建二分有向图。
g = ig.Graph(
9,
[(0, 4), (0, 5), (1, 4), (1, 6), (1, 7), (2, 5), (2, 7), (2, 8), (3, 6), (3, 7)],
directed=True
)
- We assign:
节点 0-3 到一侧
节点 4-8 到另一边
g.vs[range(4)]["type"] = True
g.vs[range(4, 9)]["type"] = False
然后我们添加一个源点(顶点9)和一个汇点(顶点10)
g.add_vertices(2)
g.add_edges([(9, 0), (9, 1), (9, 2), (9, 3)]) # connect source to one side
g.add_edges([(4, 10), (5, 10), (6, 10), (7, 10), (8, 10)]) # ... and sinks to the other
flow = g.maxflow(9, 10)
print("Size of maximum matching (maxflow) is:", flow.value)
Size of maximum matching (maxflow) is: 4.0
让我们将输出与 igraph.Graph.maximum_bipartite_matching() 进行比较:
# delete the source and sink, which are unneeded for this function.
g2 = g.copy()
g2.delete_vertices([9, 10])
matching = g2.maximum_bipartite_matching()
matching_size = sum(1 for i in range(4) if matching.is_matched(i))
print("Size of maximum matching (maximum_bipartite_matching) is:", matching_size)
Size of maximum matching (maximum_bipartite_matching) is: 4
最后,我们可以将原始流程图与添加的匹配项一起美观地显示出来。 为了实现令人愉悦的视觉效果,我们手动设置了源和汇的位置:
layout = g.layout_bipartite()
layout[9] = (2, -1)
layout[10] = (2, 2)
fig, ax = plt.subplots()
ig.plot(
g,
target=ax,
layout=layout,
vertex_size=30,
vertex_label=range(g.vcount()),
vertex_color=["lightblue" if i < 9 else "orange" for i in range(11)],
edge_width=[1.0 + flow.flow[i] for i in range(g.ecount())]
)
plt.show()

脚本的总运行时间: (0 分钟 0.377 秒)