如何创建接受 numVertices 和 numEdges 的函数,然后始终生成连通图?

How do I make a function that accepts numVertices and numEdges then ALWAYS generates a connected graph?

我不知道现有的库,但这是一个从头开始的解决方案。假设您有 n 个节点和 m 条边。要生成一个简单(无重复边)的连通图,m,n 必须满足这个条件:

n - 1 <= m <= n * (n - 1) / 2

进程(节点索引从 0 到 n - 1):

  1. 生成生成树以确保图是连通的。方法有很多种(比如Prufer序列),这里介绍一个简单的方法:

for i = 1 to n - 1: add_edge(i, randint(0, i - 1))

为了让它看起来更随机,您可以先打乱节点的顺序。

  1. 添加更多边,直到有 m 条边。

while there are less than m edges: a, b = randint(0, n - 1), randint(0, n - 1) if (a != b and edge(a, b) has not existed): add_edge(a, b)

注意:randint(a, b) = [a, b] 范围内的随机整数。

这些代码看起来很简单,但在实践中速度非常快。您可以计算预期的迭代次数以了解原因。