简体   繁体   English

有向图 - 如何计算图中每个其他顶点可到达的顶点数?

[英]Directed Graph - How to count the number of vertices from which each other vertex in graph is reachable?

在有向图中如何有效地计算图中每个其他顶点可到达的顶点数?

If there is no cycle in the graph, there can be only one such vertex and it has an in-degree zero, and there are no other vertices with an in-degree zero. 如果图中没有循环,则只能有一个这样的顶点并且它具有度为零,并且没有其他具有度为零的顶点。 You then have to run a DFS to check if all other vertices are reachable from it. 然后,您必须运行DFS以检查是否可以从其中访问所有其他顶点。 So the answer is either one or zero, depending on the result of DFS. 所以答案是一个或零,取决于DFS的结果。

If there is a cycle, then all the vertices in the cycle have this property or none of them have it. 如果存在循环,则循环中的所有顶点都具有此属性,或者它们都没有。

If you detect a cycle, replace all the vertices in the cycle with one vertex and keep a label for that vertex of how many vertices it represents. 如果检测到一个循环,则用一个顶点替换循环中的所有顶点,并为该顶点保留一个标签,表示它所代表的顶点数。 Use the same procedure as above. 使用与上面相同的步骤。 Ie, check in-degrees and run DFS from the new node. 即,检查度数并从新节点运行DFS。 The answer will be zero or the label. 答案是零或标签。

Detecting a cycle can be accomplished using a DFS. 可以使用DFS完成检测循环。

There might be several cycles in the graph. 图中可能有几个周期。 In that case you have to eliminate all of them. 在这种情况下,你必须消除所有这些。 You can eliminate all of them in one linear pass of DFS, but that's tricky. 您可以在DFS的一次线性传递中消除所有这些,但这很棘手。 You could also use Tarjan's algorithm as suggested by btilly in his answer. 您也可以使用他的答案中的btilly建议的Tarjan算法。

Use Tarjan's strongly connected components algorithm to detect all loops then construct a graph with each strongly connected component collapsed to a single node. 使用Tarjan的强连接组件算法来检测所有循环,然后构建一个图,每个强连接组件都折叠到一个节点。

Now in this new graph, it is sufficient to look for a vertex with no in edges. 现在在这个新图中,找到一个没有边的顶点就足够了。 If that vertex connects to every other one (verifiable with a breadth first linear search), then everything in the strongly connected component that it came from is in your set, otherwise no vertex is in your set. 如果该顶点连接到每个其他顶点(可通过宽度优先的线性搜索进行验证),那么它所来自强连接组件中的所有内容都在您的集合中,否则您的集合中没有顶点。

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

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