最大二分匹配

本示例演示了使用 igraph.Graph.maximum_bipartite_matching() 查找和可视化最大二分匹配的高效方法。

import igraph as ig
import matplotlib.pyplot as plt
首先,我们构建一个二分图,将
  • 节点 0-4 分配到一边

  • 节点 5-8 分配到另一边

g = ig.Graph.Bipartite(
    [0, 0, 0, 0, 0, 1, 1, 1, 1],
    [(0, 5), (1, 6), (1, 7), (2, 5), (2, 8), (3, 6), (4, 5), (4, 6)]
)

我们可以很容易地检查该图是否确实是二分图

assert g.is_bipartite()

现在可以计算最大二分匹配

打印匹配的顶点对很容易

matching_size = 0
print("Matching is:")
for i in range(5):
    print(f"{i} - {matching.match_of(i)}")
    if matching.is_matched(i):
        matching_size += 1
print("Size of maximum matching is:", matching_size)
Matching is:
0 - 5
1 - 7
2 - 8
3 - 6
4 - None
Size of maximum matching is: 4

最后,我们可以绘制二分图,用红色突出显示连接最大匹配的边

fig, ax = plt.subplots(figsize=(7, 3))
ig.plot(
    g,
    target=ax,
    layout=g.layout_bipartite(),
    vertex_size=30,
    vertex_label=range(g.vcount()),
    vertex_color="lightblue",
    edge_width=[3 if e.target == matching.match_of(e.source) else 1.0 for e in g.es],
    edge_color=["red" if e.target == matching.match_of(e.source) else "black" for e in g.es]
)
bipartite matching
<igraph.drawing.matplotlib.graph.GraphArtist object at 0x7d2bb8ef3250>

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

此图库由 Sphinx-Gallery 生成