How to generate random graphs?

后端 未结 3 2050
一个人的身影
一个人的身影 2020-12-29 11:40

I want to be able to generate random, undirected, and connected graphs in Java. In addition, I want to be able to control the maximum number of vertices in the graph. I am n

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 12:17

    Whatever you want to do with your graph, I guess its density is also an important parameter. Otherwise, you'd just generate a set of small cliques (complete graphs) using random sizes, and then connect them randomly.

    If I'm correct, I'd advise you to use the Erdős-Rényi model: it's simple, not far from what you originally proposed, and allows you to control the graph density (so, basically: the number of links).

    Here's a short description of this model:

    1. Define a probability value p (the higher p and the denser the graph: 0=no link, 1=fully connected graph);
    2. Create your n nodes (as objects, as an adjacency matrix, or anything that suits you);
    3. Each pair of nodes is connected with a (independent) probability p. So, you have to decide of the existence of a link between them using this probability p. For example, I guess you could ranbdomly draw a value q between 0 and 1 and create the link iff q < p. Then do the same thing for each possible pair of nodes in the graph.

    With this model, if your p is large enough, then it's highly probable your graph is connected (cf. the Wikipedia reference for details). In any case, if you have several components, you can also force its connectedness by creating links between nodes of distinct components. First, you have to identify each component by performing breadth-first searches (one for each component). Then, you select pairs of nodes in two distinct components, create a link between them and consider both components as merged. You repeat this process until you've got a single component remaining.

提交回复
热议问题