简体   繁体   English

使无向图有向

[英]Make undirected graph directed

I've got a undirected, complete graph and would like to convert it to a directed acyclic graph with a (unidirectional) path between each node. 我有一个无向的完整图,并希望将其转换为在每个节点之间具有(单向)路径的有向无环图。 To start off, I want to add random edges and stop once all nodes are connected. 首先,我想添加随机边缘,并在连接所有节点后停止。 What would be an algorithm to look at (using Python, but any language will do). 要看的算法是什么(使用Python,但是任何语言都可以)。

So for instance this graph, does not to be connected any further: 因此,例如,此图不再连接:

A  ---- B            A ---> B
 \     /      =>           /
  \   /                   v
    C                    C

, but in this case, all undirected edges turn into a directed edge ,但在这种情况下,所有未定向的边都变成有向边

A  ---- B            A ---> B
 \     /      =>      ^     ^
  \   /                \   /
    C                    C

Update 更新

Note that the aim is to convert an undirected graph into a directed graph as per the above constraints. 请注意,其目的是按照上述约束将无向图转换为有向图。 Like for a spanning tree, there are more than 1 solutions to this conversion process (as shown in above example). 就像生成树一样,此转换过程有多个解决方案(如上例所示)。

You need a directed spanning tree. 您需要一个定向生成树。

It's easy to find a directed spanning tree in an undirected graph. 在无向图中找到有向生成树很容易。 Just do depth-first-search, ignoring back and cross edges. 只需进行深度优先搜索,即可忽略背面和交叉边缘。 The edges you actually traverse form a directed tree that touches every node in each connected component. 您实际遍历的边缘形成一棵有向树,该树触及每个连接组件中的每个节点。

However you have added the restriction that you want edge choice to be random. 但是,您添加了希望边缘选择随机的限制。

So for this you can use a Minimum Spanning Tree algorithm like Kruskal's algorithm with random edge weights. 因此,为此,您可以使用最小生成树算法,例如具有随机边缘权重的Kruskal算法

Note there is no reason to actually store and compute random edge weights. 注意,没有理由实际存储和计算随机边缘权重。 The first step of the algorithm is to sort by weight. 该算法的第一步是按重量排序。 So replace this sort by a random permutation of the edges, and you're in business. 因此,将这种类型替换为边缘的随机排列,您就可以从事业务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM