最大二分匹配

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

import igraph as ig
import matplotlib.pyplot as plt
First, we construct a bipartite graph, assigning:
  • 节点 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 = g.maximum_bipartite_matching()

很容易打印匹配的顶点对

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 0x7fa6d26d5190>

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

Gallery generated by Sphinx-Gallery