简体   繁体   中英

Design a O(|V | + |E|) time algorithm that finds a root vertex (or reports that none exists) of a directed graph

Given a directed graph G = (V, E). A root vertex in G is a vertex v such that any other vertex u in G is reachable from v through a directed path. How to design a O(|V| + |E|) time algorithm that finds a root vertex (or reports that none exists).

Here`s O(|V| + |E|) approach:

  1. First we can join all nodes that belong to same SCC (Strongly Connected Component) to super-nodes and build new graph based on that, let's call it SCC-graph (it's also known as condensation graph, can be done with Kosaraju algorithm in O(|V| + |E|))
  2. Because SCC-graph cannot have cycles by definition it`sa DAG
  3. For every node in SCC-graph we can calculate it's in-degree (number of edges directed to it)
  4. Now if there's more than 1 node in SCC-graph with in-degree of 0 there's no root
  5. If there is only one node in SCC-graph with in-degree of 0 then any node from original graph that's part of SCC-graph node with 0 in-degree can be a root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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