From https://algs4.cs.princeton.edu/42digraph/
- Reachable vertex in a digraph. Design a linear-time algorithm to determine whether a digraph has a vertex that is reachable from every other vertex.
Kosaraju-Sharir algorithm gives us the strongly connected components. Java code for that can be seen here. Reducing each SCC to a single vertex, a vertex that has outdegree zero is reachable from every other.
Problem is, everyone seems to be talking about reducing a SCC without providing details. What is an efficient algorithm to do so?
Suppose you already have a method to compute
SCC
s and the usual graph, vertex and edge methods. Then it's just creating a new graph, adding a vertex representative for each SCC and then adding edge representatives.For the edges you need to be able to map an original vertex (the edge destination) to its representative in the new graph. You can model that in the first pass using a
Map<Vertex, SCC>
which maps vertices to their SCCs and aMap<SCC, Vertex>
which maps SCCs to their representative vertices in the new graph. Or you directly have aMap<Vertex, Vertex>
mapping original vertices to their representatives.Here is a Java solution:
Time complexity is linear in the size of the graph (amount of vertices and edges), so optimal. That is
Theta(|V| + |E|)
.Usually people use a Union-Find (see Wikipedia) data-structure to make this even simpler and get rid of the
Map
s.Following is a Java solution to my own question. For the graph representation, it uses
edu.princeton.cs:algs4:1.0.3
from https://github.com/kevin-wayne/algs4. There appears to be general algorithms for graph contraction, as outlined in this paper; however, for my purposes, the following is sufficient.Running it on the graph below produces the strongly-connected components as shown. Vertex 0 in the reduced DAG is reachable from every other vertex.
What I couldn't find anywhere is the kind of detail that I presented above. Comments like "well, this is easy, you do that, then you do something else" are thrown around without concrete details.